forked from dimitar9/Algorithm_Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_tree_level_order_2.cpp
More file actions
34 lines (31 loc) · 958 Bytes
/
binary_tree_level_order_2.cpp
File metadata and controls
34 lines (31 loc) · 958 Bytes
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
/**
* 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) {
if (!root) {return vector<vector<int> >();}
vector<pair<TreeNode*,int> > q;
int lev=1;
int count=0;
q.push_back(make_pair(root,lev));
while (count<q.size()){
TreeNode *node = q[count].first;
lev = q[count].second;
if (node->left){ q.push_back(make_pair(node->left,lev+1));}
if (node->right){ q.push_back(make_pair(node->right,lev+1));}
count++;
}
vector<vector<int> > res(lev, vector<int>());
for (int i=0;i<q.size();i++){
res[lev-q[i].second].push_back(q[i].first->val);
}
return res;
}
};