-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathBinary_Tree_Level_Order_Traversal_II.cpp
47 lines (44 loc) · 1.47 KB
/
Binary_Tree_Level_Order_Traversal_II.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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int maxHeight(TreeNode* root) {
if(!root) return 0;
return 1 + max(maxHeight(root->left), maxHeight(root->right));
}
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector < vector<int> > result;
if(!root) return result;
int height = maxHeight(root);
result.resize(height);
queue < pair <TreeNode*, int> > Q;
int prev_level = 0, curr_level;
Q.push(make_pair(root, 1));
vector <int> container;
while(!Q.empty()) {
pair <TreeNode*, int> node = Q.front();
Q.pop();
TreeNode *curr = node.first;
curr_level = node.second;
if(curr_level > prev_level) {
if(container.size() > 0) {
result[--height] = container;
}
container.clear();
}
container.push_back(curr->val);
if(curr->left) Q.push(make_pair(curr->left, curr_level + 1));
if(curr->right) Q.push(make_pair(curr->right, curr_level + 1));
prev_level = curr_level;
}
if(container.size() > 0) result[--height] = container;
return result;
}
};