-
Notifications
You must be signed in to change notification settings - Fork 119
/
107.cpp
76 lines (65 loc) · 1.91 KB
/
107.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
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> > ret;
vector<int> t;
queue<TreeNode *> q;
if (!root) return ret;
q.push(root);
int next = 0; // number of nodes in next level, includling NULL nodes
int cur = 1; // number of nodes in current level, including NULL nodes
int count = 0; // count of nodes already traversed in current level
while (!q.empty()) {
TreeNode *p = q.front();
q.pop();
if (p){// push children into queue if parent is not NULL
t.push_back(p->val);
q.push(p->left);
q.push(p->right);
next += 2;
}
count++;
if (count == cur && !t.empty()) {
ret.push_back(t);
t.clear();
cur = next;
count = next = 0;
}
}
reverse(ret.begin(), ret.end()); //reverse result vector
return ret;
}
};
int main() {
TreeNode *root = new TreeNode(1);
TreeNode *p = root;
p->left = new TreeNode(2);
p->right = new TreeNode(3);
p = p->right;
p->left = new TreeNode(4);
p = p->left;
p->right = new TreeNode(5);
p = p->right;
p->left = new TreeNode(6);
p->right = new TreeNode(7);
Solution s;
vector<vector<int> > ret = s.levelOrderBottom(root);
for (int i = 0; i < ret.size(); i++) {
for (int j = 0; j < ret[i].size(); j++) {
cout << ret[i][j];
}
cout << endl;
}
return 0;
}