We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static void topView(Node root) {
if (root == null) {
return;
}
Queue> queue = new LinkedList<>();
// Map to store the first node at each horizontal distance
Map map = new TreeMap<>();
// Start with the root node and horizontal distance 0
queue.offer(new AbstractMap.SimpleEntry<>(root, 0));
while (!queue.isEmpty()) {
Map.Entry<Node, Integer> entry = queue.poll();
Node node = entry.getKey();
int horizontalDistance = entry.getValue();
// If the horizontal distance is not yet in the map, add it
if (!map.containsKey(horizontalDistance)) {
map.put(horizontalDistance, node.data);
}
// If the node has a left child, enqueue it with horizontal distance - 1
if (node.left != null) {
queue.offer(new AbstractMap.SimpleEntry<>(node.left, horizontalDistance - 1));
}
// If the node has a right child, enqueue it with horizontal distance + 1
if (node.right != null) {
queue.offer(new AbstractMap.SimpleEntry<>(node.right, horizontalDistance + 1));
}
}
// Print the top view by iterating over the map
for (int value : map.values()) {
System.out.print(value + " ");
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
public static void topView(Node root) { if (root == null) { return;
Queue> queue = new LinkedList<>(); // Map to store the first node at each horizontal distance Map map = new TreeMap<>();