-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathtree.cpp
77 lines (77 loc) · 1.75 KB
/
tree.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
77
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
struct Bucket {
TreeNode *node;
int level;
Bucket(TreeNode *p, int l) : node(p), level(l){}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
vector<vector<int>> result;
if (root == nullptr)
return result;
queue<Bucket> q;
result.push_back(vector<int>());
int curLevel = 0;
q.push(Bucket(root, 0));
while (!q.empty()) {
Bucket bucket = q.front();
q.pop();
TreeNode *p = bucket.node;
int level = bucket.level;
if (level != curLevel) {
result.push_back(vector<int>());
curLevel++;
}
result[curLevel].push_back(p->val);
if (p->left)
q.push(Bucket(p->left, level + 1));
if (p->right)
q.push(Bucket(p->right, level + 1));
}
reverse(result.begin(), result.end());
}
};
TreeNode *mk_node(int val)
{
return new TreeNode(val);
}
TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right)
{
root->left = left;
root->right = right;
return root;
}
TreeNode *mk_child(TreeNode *root, int left, int right)
{
return mk_child(root, new TreeNode(left), new TreeNode(right));
}
TreeNode *mk_child(int root, int left, int right)
{
return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right));
}
int main(int argc, char **argv)
{
Solution solution;
TreeNode *root = mk_child(1, 2, 3);
mk_child(root->left, 4, 5);
auto results = solution.levelOrderBottom(root);
for (auto result : results) {
for_each(result.begin(), result.end(), [](int i){cout << i << " ";});
cout << endl;
}
return 0;
}