0%

从上往下打印二叉树

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

从上到下一层一层即广度优先,即队列。

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
/*
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> result;
queue<TreeNode*> nodes;
nodes.push(root);
while(nodes.size())
{
TreeNode *next = nodes.front();
nodes.pop();
if (next != nullptr)
{
result.push_back(next->val);
nodes.push(next->left);
nodes.push(next->right);
}
}
return result;
}
};