-
Notifications
You must be signed in to change notification settings - Fork 14
/
Solution103.java
40 lines (34 loc) · 1.08 KB
/
Solution103.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
package leetcode.tree.levelorder;
import leetcode.TreeNode;
import java.util.ArrayDeque;
import java.util.LinkedList;
import java.util.List;
public class Solution103 {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new LinkedList<>();
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
LinkedList<Integer> level = new LinkedList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (res.size() % 2 == 0) {
level.addLast(node.val);
} else {
level.addFirst(node.val);
}
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
res.add(level);
}
return res;
}
}