-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
56 lines (50 loc) · 1.18 KB
/
solution.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
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)
{
vector<vector<int> > result;
vector<int> temp;
queue<TreeNode *> q;
int count = 1;
int nextCount = 0;
if(root == NULL)
return result;
q.push(root);
while(!q.empty())
{
temp.push_back(q.front()->val);
count--;
if(q.front()->left)
{
q.push(q.front()->left);
nextCount++;
}
if(q.front()->right)
{
q.push(q.front()->right);
nextCount++;
}
q.pop();
if(count == 0)
{
result.push_back(temp);
temp.resize(0);
count = nextCount;
nextCount = 0;
}
}
for(int i=0,j=result.size()-1;i<j;i++,j--)
swap(result[i],result[j]);
return result;
}
};