File tree 1 file changed +64
-0
lines changed
1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6
+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7
+ < title > Document</ title >
8
+ </ head >
9
+ < body >
10
+ < script >
11
+ // Source : https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
12
+ // Author : 悬笔e绝
13
+ // Date : 2019-03-27
14
+
15
+ // Definition for a binary tree node.
16
+ function TreeNode ( val ) {
17
+ this . val = val ;
18
+ this . left = this . right = null ;
19
+ }
20
+
21
+ /**
22
+ * @param {TreeNode } root
23
+ * @return {number[][] }
24
+ */
25
+ var zigzagLevelOrder = function ( root ) {
26
+ var maxn = - 1 ;
27
+ var ans = [ ] ;
28
+ dfs ( root , 0 ) ;
29
+
30
+ function dfs ( node , step ) {
31
+ if ( ! node )
32
+ return ;
33
+ maxn = step > maxn ? step : maxn ;
34
+ if ( ! ans [ step ] )
35
+ ans [ step ] = [ ] ;
36
+ ans [ step ] . push ( node . val ) ;
37
+ dfs ( node . left , step + 1 ) ;
38
+ dfs ( node . right , step + 1 ) ;
39
+ }
40
+
41
+ for ( var i = 0 ; i <= maxn ; i ++ )
42
+ ( i & 1 ) && ( ans [ i ] . reverse ( ) ) ;
43
+ return ans ;
44
+ } ;
45
+
46
+ // 测试
47
+ var tree_node_1_1 = new TreeNode ( 9 ) ;
48
+ var tree_node_1_2 = new TreeNode ( 20 ) ;
49
+ tree_node_1_2 . left = new TreeNode ( 15 ) ;
50
+ tree_node_1_2 . right = new TreeNode ( 7 ) ;
51
+ var tree_node_1 = new TreeNode ( 3 ) ;
52
+ tree_node_1 . left = tree_node_1_1 ;
53
+ tree_node_1 . right = tree_node_1_2 ;
54
+ console . log ( zigzagLevelOrder ( tree_node_1 ) ) ;
55
+
56
+ // [
57
+ // [3],
58
+ // [20,9],
59
+ // [15,7]
60
+ // ]
61
+
62
+ </ script >
63
+ </ body >
64
+ </ html >
You can’t perform that action at this time.
0 commit comments