/*
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;
queue<TreeNode *> que;
TreeNode *cur;
if(!root) return res;
que.push(root);
while(!que.empty())
{
cur=que.front();
que.pop();
if(cur->left)que.push(cur->left);
if(cur->right)que.push(cur->right);
res.push_back(cur->val);
}
return res;
}
};
最直观的想法是,层次遍历,使用辅助队列进行层次遍历。使用res存储遍历结果,使用que辅助存储二叉树,使用cur表示当前队列的头节点。首先判断根结点root是否为空,如果是则直接返回空的res,反之将头节点加入到队列中,当队列不为空,就使用cur接收队列的头节点,然后将头节点弹出来,并且当头结点的左孩子不为空则将左孩子加入队列,头孩子的右节点不为空则将右孩子加入队列,接着将头节点的值加入结果数组中,最后返回res即可。



京公网安备 11010502036488号