+从上往下打印出二叉树的每个节点,同层节点从左至右打印。
- 层次遍历
- C++ 代码
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
if(!root) return {};
vector <int> vec;
queue<TreeNode *> q;
st.push(root);
while(!st.empty())
{
TreeNode* tmp=q.front();
vec.push_back(tmp->val);
st.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
return vec;
}
};
网友评论