forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
74 lines (57 loc) · 1.54 KB
/
main2.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
/// Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
/// Author : liuyubobobo
/// Time : 2018-10-16
#include <iostream>
using namespace std;
#include <iostream>
#include <vector>
#include <queue>
#include <cassert>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// BFS
/// No need to store level information in the queue :-)
///
/// Time Complexity: O(n), where n is the number of nodes in the tree
/// Space Complexity: O(n)
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if(root == NULL)
return res;
queue<TreeNode*> q;
q.push(root);
int level_num = 1;
while(!q.empty()){
int new_level_num = 0;
vector<int> level;
for(int i = 0; i < level_num; i ++){
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if(node->left){
q.push(node->left);
new_level_num ++;
}
if(node->right){
q.push(node->right);
new_level_num ++;
}
}
res.push_back(level);
level_num = new_level_num;
}
reverse(res.begin(), res.end());
return res;
}
};
int main() {
return 0;
}