-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZigZagTraversal.java
More file actions
85 lines (64 loc) · 2.31 KB
/
Copy pathZigZagTraversal.java
File metadata and controls
85 lines (64 loc) · 2.31 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
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
package gliderai;
import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
left = right = null;
}
}
public class ZigZagTraversal {
public static int[] getLevelSpiral(TreeNode root) {
if (root == null)
return new int[0];
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean leftToRight = true; // Start with left to right
while (!queue.isEmpty()) {
int levelSize = queue.size();
Deque<Integer> levelNodes = new LinkedList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
if (leftToRight) {
levelNodes.addLast(node.val); // Left to Right
} else {
levelNodes.addFirst(node.val); // Right to Left
}
if (node.left != null)
queue.offer(node.left);
if (node.right != null)
queue.offer(node.right);
}
result.addAll(levelNodes);
leftToRight = !leftToRight; // Toggle direction
}
return result.stream().mapToInt(i -> i).toArray(); // Convert List to int[]
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // Number of edges
Map<Integer, TreeNode> nodes = new HashMap<>();
TreeNode root = null;
for (int i = 0; i < n; i++) {
int parent = sc.nextInt();
int child = sc.nextInt();
char direction = sc.next().charAt(0); // 'L' or 'R'
nodes.putIfAbsent(parent, new TreeNode(parent));
nodes.putIfAbsent(child, new TreeNode(child));
TreeNode parentNode = nodes.get(parent);
TreeNode childNode = nodes.get(child);
if (direction == 'L') {
parentNode.left = childNode;
} else {
parentNode.right = childNode;
}
if (root == null)
root = parentNode;
}
sc.close();
int[] zigzagOrder = getLevelSpiral(root);
System.out.println(Arrays.toString(zigzagOrder));
}
}