CodingInterview-把二叉树打印成多行

使用层序遍历,并使用两个指针跟踪每一层的 Node 个数即可。

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
33
34
35
36
37
38
39
40
41
42
43
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> result;
if(pRoot==NULL) return result;
queue<TreeNode*> q;
q.push(pRoot);
int now=1,next=0;
vector<int>* v=new vector<int>();
while(!q.empty()){
TreeNode* t=q.front();
q.pop();
now--;
v->push_back(t->val);
if(t->left!=NULL) {
q.push(t->left);
next++;
}
if(t->right!=NULL) {
q.push(t->right);
next++;
}
if(now==0){
now=next;
next=0;
result.push_back(*v);
v=new vector<int>();
}
}
return result;
}

};