OJ链接:二叉树层序遍历
题目描述
- 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
- 借助queue完成。
代码
/*
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==nullptr)
return vector<int> ();
vector<int> v;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode *father = q.front();
q.pop();
v.push_back(father->val);
if(father->left)
{
//左子树不为空
q.push(father->left);
}
if(father->right)
{
//右子树不为空
q.push(father->right);
}
}
return v;
}
};