-
Notifications
You must be signed in to change notification settings - Fork 62
/
Solution.java
64 lines (61 loc) · 1.84 KB
/
Solution.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
package g0101_0200.s0103_binary_tree_zigzag_level_order_traversal;
// #Medium #Top_Interview_Questions #Breadth_First_Search #Tree #Binary_Tree
// #Data_Structure_II_Day_15_Tree #Udemy_Tree_Stack_Queue
// #2022_06_22_Time_1_ms_(95.00%)_Space_43.2_MB_(19.22%)
import com_github_leetcode.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/*
* 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;
* }
* }
*/
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(null);
boolean zig = true;
LinkedList<Integer> level = new LinkedList<>();
while (!q.isEmpty()) {
TreeNode node = q.remove();
while (!q.isEmpty() && node != null) {
if (zig) {
level.add(node.val);
} else {
level.addFirst(node.val);
}
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
node = q.remove();
}
result.add(level);
zig = !zig;
level = new LinkedList<>();
if (!q.isEmpty()) {
q.add(null);
}
}
return result;
}
}