File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ ``` javascript
2
+ public ArrayList< ArrayList< Integer>> zigzagLevelOrder (TreeNode root ) {
3
+ ArrayList< ArrayList< Integer>> res = new ArrayList < ArrayList< Integer>> ();
4
+ Stack< TreeNode> stack1 = new Stack < TreeNode> ();
5
+ Stack< TreeNode> stack2 = new Stack < TreeNode> ();
6
+ int layer = 1 ;// 层数
7
+ stack1 .push (root);
8
+ while (! stack1 .isEmpty () || ! stack2 .isEmpty ()){
9
+ if (layer% 2 != 0 ){// 奇数层
10
+ ArrayList< Integer> list = new ArrayList < Integer> ();
11
+ while (! stack1 .isEmpty ()){
12
+ TreeNode node = stack1 .pop ();
13
+ if (node != null ){
14
+ list .add (node .val );
15
+ stack2 .push (node .left );// 从左到右
16
+ stack2 .push (node .right );
17
+ }
18
+ }
19
+ if (! list .isEmpty ()){
20
+ res .add (list);
21
+ layer++ ;
22
+ }
23
+ }else {// 偶数层
24
+ ArrayList< Integer> list = new ArrayList < Integer> ();
25
+ while (! stack2 .isEmpty ()){
26
+ TreeNode node = stack2 .pop ();
27
+ if (node != null ){
28
+ list .add (node .val );
29
+ stack1 .push (node .right );// 从右到左
30
+ stack1 .push (node .left );
31
+ }
32
+ }
33
+ if (! list .isEmpty ()){
34
+ res .add (list);
35
+ layer++ ;
36
+ }
37
+ }
38
+ }
39
+
40
+ return res;
41
+ }
42
+ ```
You can’t perform that action at this time.
0 commit comments