File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val) {
4
+ * this.val = val;
5
+ * this.left = this.right = null;
6
+ * }
7
+ */
8
+ /**
9
+ * @param {TreeNode } root
10
+ * @return {number[][] }
11
+ */
12
+ const zigzagLevelOrder = function ( root ) {
13
+ if ( root == null ) return [ ]
14
+ const row = [ root ]
15
+ const res = [ ]
16
+ bfs ( row , res )
17
+ for ( let i = 0 ; i < res . length ; i ++ ) {
18
+ res [ i ] = i % 2 === 0 ? res [ i ] : res [ i ] . reverse ( )
19
+ }
20
+ return res
21
+ } ;
22
+
23
+ function bfs ( row , res ) {
24
+ if ( row . length === 0 ) return
25
+ let tmp = [ ]
26
+ let next = [ ]
27
+ for ( let i = 0 ; i < row . length ; i ++ ) {
28
+ tmp . push ( row [ i ] . val )
29
+ if ( row [ i ] . left ) {
30
+ next . push ( row [ i ] . left )
31
+ }
32
+ if ( row [ i ] . right ) {
33
+ next . push ( row [ i ] . right )
34
+ }
35
+ }
36
+ if ( tmp . length ) {
37
+ res . push ( tmp )
38
+ }
39
+ bfs ( next , res )
40
+ }
You can’t perform that action at this time.
0 commit comments