-
Notifications
You must be signed in to change notification settings - Fork 1
/
032_02-把二叉树打印成多行.cpp
49 lines (44 loc) · 1.33 KB
/
032_02-把二叉树打印成多行.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
42
43
44
45
46
47
48
49
/*
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>> res;
if(pRoot==nullptr)
return res;
int currentLevelNum=1;
int nextLevelNum=0;
queue<TreeNode*> nodeQueue;
nodeQueue.push(pRoot);
vector<int> level;
while(!nodeQueue.empty()){
TreeNode* node=nodeQueue.front();
nodeQueue.pop();
currentLevelNum--;
level.push_back(node->val);
if(node->left!=nullptr){
nodeQueue.push(node->left);
nextLevelNum++;
}
if(node->right!=nullptr){
nodeQueue.push(node->right);
nextLevelNum++;
}
if(currentLevelNum==0){
res.push_back(level);
vector<int>().swap(level);
currentLevelNum=nextLevelNum;
nextLevelNum=0;
}
}
return res;
}
};