-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0103-binary-tree-zigzag-level-order-traversal.java
More file actions
43 lines (42 loc) · 1.3 KB
/
0103-binary-tree-zigzag-level-order-traversal.java
File metadata and controls
43 lines (42 loc) · 1.3 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
/**
* 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>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root == null) return new ArrayList<>();
q.offer(root);
boolean LTR = false; //left to right, changes every level
while (!q.isEmpty()) {
int size = q.size();
List<Integer> lst = new ArrayList<>();
for (int i=0; i<size; i++) {
TreeNode curr = q.poll();
if (LTR) { //add from the left
lst.add(0, curr.val);
}
else { //add fomr the right
lst.add(curr.val);
}
if (curr.left != null) q.offer(curr.left);
if (curr.right != null) q.offer(curr.right);
}
LTR = !LTR; //swap sides
res.add(lst);
}
return res;
}
}