思路:定义一个二叉树结点队列和一个整形数组,先将树根压入队列,然后依次弹出队列头的结点,将结点的值传入整型数组,同时判断新弹出的结点如果由左右子树,则按次序依次压入队列尾。这样循环进行,直到队列为空,之后输出整型数组。注意判断树是不是一个空树。
源代码:
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> res;
queue<TreeNode*> que;
TreeNode* f;
if(root==NULL)
return res;
que.push(root);
while(!que.empty())
{
f=que.front();
if(f->left!=NULL)
que.push(f->left);
if(f->right!=NULL)
que.push(f->right);
res.push_back(f->val);
que.pop();
}
return res;
}
};