-
Notifications
You must be signed in to change notification settings - Fork 0
/
把二叉树打印成多行.cpp
41 lines (37 loc) · 1.18 KB
/
把二叉树打印成多行.cpp
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
//从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
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(0);
if (!pRoot)
return result;
vector<TreeNode*> cur(0);
cur.push_back(pRoot);
while(cur.size() > 0) {
vector<int> curVal(0);
for (int i = 0; i < cur.size(); ++i)
curVal.push_back(cur[i]->val);
result.push_back(curVal);
vector<TreeNode*> temp(0);
for (int i = 0; i < cur.size(); ++i) {
if (cur[i]->left)
temp.push_back(cur[i]->left);
if (cur[i]->right)
temp.push_back(cur[i]->right);
}
swap(temp, cur);
vector<int>(0).swap(curVal);
}
return result;
}
};