-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day45.java
91 lines (73 loc) · 2.27 KB
/
Day45.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
87
88
89
90
91
/* Binary Tree Zigzag Level Order Traversal */
import java.util.*;
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>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean isLeftToRight = true;
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> currentLevel = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
// Add the node value based on the traversal direction
if (isLeftToRight) {
currentLevel.add(node.val);
} else {
currentLevel.add(0, node.val); // Insert at the beginning of the list
}
// Enqueue the child nodes
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
// Toggle the traversal direction
isLeftToRight = !isLeftToRight;
result.add(currentLevel);
}
return result;
}
}
public class Day45 {
public static void main(String[] args) {
/*
3
/ \
9 20
/ \
15 7
*/
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
Solution solution = new Solution();
List<List<Integer>> result = solution.zigzagLevelOrder(root);
// Print the zigzag level order traversal
for (List<Integer> level : result) {
System.out.println(level);
}
}
}