File tree Expand file tree Collapse file tree 2 files changed +75
-1
lines changed
0107-Binary-Tree-Level-Order-Traversal-II/cpp-0107 Expand file tree Collapse file tree 2 files changed +75
-1
lines changed Original file line number Diff line number Diff line change @@ -3,5 +3,5 @@ project(cpp_0107)
3
3
4
4
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
5
5
6
- set (SOURCE_FILES main .cpp )
6
+ set (SOURCE_FILES main2 .cpp )
7
7
add_executable (cpp_0107 ${SOURCE_FILES} )
Original file line number Diff line number Diff line change
1
+ // / Source : https://leetcode.com/problems/binary-tree-level-order-traversal-ii/description/
2
+ // / Author : liuyubobobo
3
+ // / Time : 2018-10-16
4
+
5
+ #include < iostream>
6
+
7
+ using namespace std ;
8
+
9
+ #include < iostream>
10
+ #include < vector>
11
+ #include < queue>
12
+ #include < cassert>
13
+
14
+ using namespace std ;
15
+
16
+
17
+ // / Definition for a binary tree node.
18
+ struct TreeNode {
19
+ int val;
20
+ TreeNode *left;
21
+ TreeNode *right;
22
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
23
+ };
24
+
25
+ // / BFS
26
+ // / No need to store level information in the queue :-)
27
+ // /
28
+ // / Time Complexity: O(n), where n is the number of nodes in the tree
29
+ // / Space Complexity: O(n)
30
+ class Solution {
31
+ public:
32
+ vector<vector<int >> levelOrderBottom (TreeNode* root) {
33
+
34
+ vector<vector<int >> res;
35
+ if (root == NULL )
36
+ return res;
37
+
38
+ queue<TreeNode*> q;
39
+ q.push (root);
40
+ int level_num = 1 ;
41
+
42
+ while (!q.empty ()){
43
+
44
+ int new_level_num = 0 ;
45
+ vector<int > level;
46
+ for (int i = 0 ; i < level_num; i ++){
47
+ TreeNode* node = q.front ();
48
+ q.pop ();
49
+ level.push_back (node->val );
50
+
51
+ if (node->left ){
52
+ q.push (node->left );
53
+ new_level_num ++;
54
+ }
55
+ if (node->right ){
56
+ q.push (node->right );
57
+ new_level_num ++;
58
+ }
59
+ }
60
+
61
+ res.push_back (level);
62
+ level_num = new_level_num;
63
+ }
64
+
65
+ reverse (res.begin (), res.end ());
66
+ return res;
67
+ }
68
+ };
69
+
70
+
71
+ int main () {
72
+
73
+ return 0 ;
74
+ }
You can’t perform that action at this time.
0 commit comments