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.
// where n is the number of nodes in the binary tree
public static void topView(Node root) {
int MAX = 500; // Otherwise, MAX=getNodeCount(root);
int[] top = new int[MAX*2];
Queue<Object[]> queue = new ArrayDeque<>();
queue.add(new Object[]{root, MAX});
while(!queue.isEmpty()) {
Object[] array = queue.remove();
Node node = (Node)array[0];
Integer order = (Integer)array[1];
if(node == null) continue;
if(top[order] == 0) top[order] = node.data;
queue.add(new Object[]{node.left, order-1});
queue.add(new Object[]{node.right, order+1});
}
for(int data: top) if(data != 0) System.out.print(data + " ");
}
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 →
Java Solution in O(n)