File tree Expand file tree Collapse file tree 1 file changed +20
-23
lines changed Expand file tree Collapse file tree 1 file changed +20
-23
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
- * 107. 二叉树的层次遍历 II
3
- *
4
- * https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
5
- *
6
- *
7
- * Easy
8
- *
9
- * 64ms 100%
10
- * 35mb 11.80%
2
+ * 时间复杂度:O(n)
3
+ * 空间复杂度:O(n)
11
4
*/
12
5
const levelOrderBottom = root => {
13
- const ans = [ ]
14
6
if ( ! root ) {
15
- return ans
7
+ return [ ] ;
16
8
}
17
- const queue = [ root ]
9
+
10
+ const ans = [ ] ;
11
+ let queue = [ root ] ;
12
+
18
13
while ( queue . length ) {
19
- const temp = [ ]
20
- const max = queue . length
21
- for ( let i = 0 ; i < max ; i ++ ) {
22
- const item = queue . pop ( )
23
- if ( item ) {
24
- temp . push ( item . val )
25
- item . left && queue . unshift ( item . left )
26
- item . right && queue . unshift ( item . right )
14
+ const len = queue . length ;
15
+ const item = [ ] ;
16
+ const _queue = [ ] ;
17
+ for ( let i = 0 ; i < len ; i ++ ) {
18
+ const currentRoot = queue [ i ] ;
19
+ item . push ( currentRoot . val ) ;
20
+
21
+ currentRoot . left && _queue . push ( currentRoot . left ) ;
22
+ currentRoot . right && _queue . push ( currentRoot . right ) ;
27
23
}
28
- }
29
- ans . unshift ( temp )
24
+ queue = _queue ;
25
+ ans . push ( item ) ;
30
26
}
31
- return ans
27
+ ans . reverse ( ) ;
28
+ return ans ;
32
29
}
You can’t perform that action at this time.
0 commit comments