题意:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解法:
题意其实就是给定树,求树的层序遍历序列.
从树根开始bfs即可,因为同层节点要从左到右打印,那么优先将左子节点丢入队列.
code:
/*
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;
q.push(root);
vector<int>ans;
while(!q.empty()){
TreeNode* x=q.front();q.pop();
if(x==NULL)continue;
ans.push_back(x->val);
q.push(x->left);
q.push(x->right);
}
return ans;
}
};