剑指offer - 从上往下打印二叉树

题目

https://www.nowcoder.com/questionTerminal/7fe2212963db4790b57431d9ed259701

题意

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

题解

二叉树的层次遍历。

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
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> ans;
if(root==NULL) return ans;
queue<TreeNode *> que;
que.push(root);
while(!que.empty()){
TreeNode * node = que.front();
ans.push_back(node->val);
que.pop();
if(node->left)
que.push(node->left);
if(node->right)
que.push(node->right);
}
return ans;
}
};