-
Notifications
You must be signed in to change notification settings - Fork 160
/
Copy pathBinary_Tree_Level_Order_Traversal_II.cc
56 lines (56 loc) · 1.52 KB
/
Binary_Tree_Level_Order_Traversal_II.cc
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
50
51
52
53
54
55
56
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<vector<int> > st;
vector<vector<int> > ans;
if (root == NULL) {
return ans;
}
vector<int> tmp;
queue<TreeNode *> q;
queue<int> dep_que;
TreeNode *cntNode;
int minDepth = 1, cntDepth;
q.push(root);
dep_que.push(1);
while (!q.empty()) {
cntNode = q.front();
q.pop();
cntDepth = dep_que.front();
dep_que.pop();
if (cntDepth > minDepth) {
st.push(tmp);
tmp.clear();
minDepth = cntDepth;
}
tmp.push_back(cntNode->val);
if (cntNode->left) {
q.push(cntNode->left);
dep_que.push(cntDepth + 1);
}
if (cntNode->right) {
q.push(cntNode->right);
dep_que.push(cntDepth + 1);
}
}
if (tmp.size() > 0) {
ans.push_back(tmp);
}
while (!st.empty()) {
ans.push_back(st.top());
st.pop();
}
return ans;
}
};