CodingInterview-从上往下打印二叉树

二叉树的层序遍历,使用队列即可。

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