从上往下打印二叉树

Desicription

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
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;
queue<TreeNode*> bfs;
if(root == nullptr) {
return res;
}
bfs.push(root);
while(!bfs.empty()) {
root = bfs.front();
bfs.pop();
if(root->left) {
bfs.push(root->left);
}
if(root->right) {
bfs.push(root->right);
}
res.push_back(root->val);
}
return res;
}
};