题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
代码
/*
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(NULL == root)
{
return res;
}
queue<TreeNode*>q;
TreeNode *p;
p = root;
q.push(p);
while(!q.empty())
{
p = q.front();
q.pop();
res.push_back(p->val);
if(p->left != NULL)
{
q.push(p->left);
}
if(p->right!=NULL)
{
q.push(p->right);
}
}
return res;
}
};
运行结果
运行时间:4ms
占用内存:488k
解题思路
按层遍历