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;
// A class to store node and its horizontal distance (hd)
class QueueNode {
Node node;
int hd;
QueueNode(Node node, int hd) {
this.node = node;
this.hd = hd;
}
}
Queue<QueueNode> queue = new LinkedList<>();
Map<Integer, Integer> topViewMap = new TreeMap<>(); // TreeMap to sort by HD
queue.add(new QueueNode(root, 0));
while (!queue.isEmpty()) {
QueueNode current = queue.poll();
int hd = current.hd;
Node node = current.node;
// Only add to map if this HD hasn't been seen yet
if (!topViewMap.containsKey(hd)) {
topViewMap.put(hd, node.data);
}
// Enqueue left child with HD-1
if (node.left != null) {
queue.add(new QueueNode(node.left, hd - 1));
}
// Enqueue right child with HD+1
if (node.right != null) {
queue.add(new QueueNode(node.right, hd + 1));
}
}
// Print the top view in left-to-right order (sorted HD)
for (Map.Entry<Integer, Integer> entry : topViewMap.entrySet()) {
System.out.print(entry.getValue() + " ");
}
}
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;
}