从上往下打印二叉树:
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:利用bfs思想,构建一个队列,每次取出队列头输出值然后找左右节点然后加入队列,直到队列为空。
对于bfs的理解可参考广度优先算法(bfs)理解+例题
/*
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> s;
if(root == NULL)return s;
TreeNode *a;
a = root;
queue<TreeNode*> q;
q.push(a);
while(!q.empty()){
a = q.front();
s.push_back(a->val);
q.pop();
if(a->left != NULL){
q.push(a->left);
}
if(a->right != NULL){
q.push(a->right);
}
}
return s;
}
};