-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBinary Tree Zigzag Level Order Traversal (bazinga)
More file actions
58 lines (58 loc) · 1.61 KB
/
Binary Tree Zigzag Level Order Traversal (bazinga)
File metadata and controls
58 lines (58 loc) · 1.61 KB
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
boolean inorder=true;
List<List<Integer>> list=new ArrayList<List<Integer>>();
if(root==null) return list;
List<Integer> level=new ArrayList<Integer>();
level.add(root.val);
list.add(level);
level=new ArrayList<Integer>();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
if(root.left!=null) queue.add(root.left);
if(root.right!=null) queue.add(root.right);
queue.add(null);
inorder=false;
while(true){
if (queue.peek()==null) {
queue.poll();
if (queue.isEmpty()) {
break;
}
if(inorder) {list.add(level);inorder=false;}
else {
list.add(reverse(level));inorder=true;
}
level=new ArrayList<Integer>();
queue.add(null);
}else{
TreeNode tmp=queue.poll();
level.add(tmp.val);
if(tmp.left!=null) queue.add(tmp.left);
if(tmp.right!=null) queue.add(tmp.right);
}
}
if(!level.isEmpty()){
if(inorder) {list.add(level);inorder=false;}
else {
list.add(reverse(level));inorder=true;
}
}
return list;
}
private List<Integer> reverse(List<Integer> list){
List<Integer> ret=new ArrayList<Integer>();
for (int i = list.size()-1; i >= 0; i--) {
ret.add(list.get(i));
}
return ret;
}
}