forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-level-order-traversal-ii.cpp
52 lines (46 loc) · 1.22 KB
/
binary-tree-level-order-traversal-ii.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
// Time: O(n)
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root : The root of binary tree.
* @return : buttom-up level order a list of lists of integer
*/
public:
vector<vector<int>> levelOrderBottom(TreeNode *root) {
vector<vector<int>> result;
queue<TreeNode *> que;
if (root != nullptr) {
que.emplace(root);
}
while (!que.empty()) {
vector<int> level;
int size = que.size();
for (int i = 0; i < size; i++) {
auto *front = que.front();
que.pop();
level.emplace_back(front->val);
if (front->left != nullptr) {
que.emplace(front->left);
}
if (front->right != nullptr) {
que.emplace(front->right);
}
}
result.emplace_back(move(level));
}
reverse(result.begin(), result.end());
return result;
}
};