题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
代码:
/*
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) {
queue<TreeNode*>q;
vector<int>res;
if(root==NULL) return res;
q.push(root);
TreeNode* now=NULL;
while(!q.empty())
{
now=q.front();
q.pop();
res.push_back(now->val);
if(now->left) q.push(now->left);
if(now->right) q.push(now->right);
}
return res;
}
};