forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
binary-tree-level-order-traversal-ii.cpp
46 lines (41 loc) · 1.2 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
// Time: O(n)
// Space: O(n)
/**
* Definition for a binary tree node.
* 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;
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));
}
// The only difference between binary-tree-level-order-traversal
// and binary-tree-level-order-traversal-ii
reverse(result.begin(), result.end());
return result;
}
};