File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ boolean reverse = false ; // flag to detrmine the direction left or right
3
+ List <List <Integer >> sol = new ArrayList <List <Integer >>();
4
+ public List <List <Integer >> zigzagLevelOrder (TreeNode root ) {
5
+ if (root == null ){return sol ;}
6
+ Queue <TreeNode > queue = new LinkedList <>();
7
+ queue .add (root );
8
+ while ( !queue .isEmpty ()){
9
+ List <Integer > temp = new ArrayList <Integer >();
10
+ int size =queue .size ();
11
+ for (int i =0 ; i < size ; i ++){
12
+ TreeNode node = queue .poll ();
13
+ temp .add (node .val );
14
+ if (node .left != null ){
15
+ queue .add (node .left );
16
+ }
17
+ if (node .right != null ){
18
+ queue .add (node .right );
19
+ }
20
+ }
21
+ if (reverse ){
22
+ Collections .reverse (temp );
23
+ }
24
+ reverse = !reverse ;
25
+ sol .add (temp );
26
+ }
27
+ return sol ;
28
+ }
29
+
30
+ }
You can’t perform that action at this time.
0 commit comments