-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC 103. Binary Tree Zigzag Level Order Traversal.java
86 lines (85 loc) · 2.67 KB
/
LC 103. Binary Tree Zigzag Level Order Traversal.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) return ans;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean rightToLeft = true;
while (!q.isEmpty()) {
rightToLeft = !rightToLeft;
int noOfNodes = q.size();
reverse(q);
List<Integer> li = new ArrayList<>();
while (noOfNodes-- > 0) {
TreeNode cur = q.poll();
li.add(cur.val);
if (!rightToLeft && cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
if (rightToLeft && cur.left != null) q.offer(cur.left);
}
ans.add(li);
}
return ans;
}
void reverse(Queue<TreeNode> q) {
Stack<TreeNode> stk = new Stack<>();
while (!q.isEmpty())
stk.push(q.poll());
while (!stk.isEmpty())
q.offer(stk.pop());
}
}
// This is actual zig-zag traversal of the tree.
// We can use this trick to maintain an ans list which looks like a zigzag traversal at the end:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) return ans;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int i = 1;
while (!q.isEmpty()) {
int noOfNodes = q.size();
List<Integer> li = new ArrayList<>();
while (noOfNodes-- > 0) {
TreeNode cur = q.poll();
li.add(cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
if ((i++) % 2 == 0) Collections.reverse(li); // the only diff compared to usual level order traversal
ans.add(li);
}
return ans;
}
}