-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzigzagLevelOrder.java
66 lines (63 loc) · 1.79 KB
/
zigzagLevelOrder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.company;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.LinkedList;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
left=null;
right=null;
}
}
public class zigzagLevelOrder {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>();
TreeNode A=new TreeNode(3);
TreeNode B=new TreeNode(9);
TreeNode C=new TreeNode(20);
TreeNode D=new TreeNode(15);
TreeNode E=new TreeNode(7);
A.left=B;
A.right=C;
C.left=D;
C.right=E;
result=zigZag(A);
System.out.println(result);
}
public static ArrayList<ArrayList<Integer>> zigZag(TreeNode A) {
ArrayList<ArrayList<Integer>> ans=new ArrayList<ArrayList<Integer>>();
if(A==null){
return ans;
}
Deque<TreeNode> q=new LinkedList<TreeNode>();
q.add(A);
TreeNode last=A;
int level=1;
ArrayList<Integer> tempList=new ArrayList<Integer>();
while(!q.isEmpty()){
TreeNode curr=q.poll();
tempList.add(curr.val);
if(curr.left!=null)q.add(curr.left);
if(curr.right!=null)q.add(curr.right);
if(last==curr){
if(level%2==0){
Collections.reverse(tempList);
ans.add(tempList);
}
else{
ans.add(tempList);
}
tempList=new ArrayList<Integer>();
if(!q.isEmpty()){
last=q.getLast();
level++;
}
}
}
return ans;
}
}