题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路详解
(1) 使用queue,利用队列先进先出的特点,首先将根节点入队列
(2) 使用while(终止条件是队列为空)
(3) 先出队列,并放入vector中(遍历)
(3) 如果左右孩子不为空就入队列
/*
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) {
vector<int> res;
if(root == NULL)
return res;
TreeNode* cur = root;
queue<TreeNode*> qu;
qu.push(cur);
while(!qu.empty())
{
cur = qu.front();
res.push_back(cur->val);
qu.pop();
if(cur->left != NULL)
{
qu.push(cur->left);
}
if(cur->right != NULL)
{
qu.push(cur->right);
}
}
return res;
}
};