You are viewing a single comment's thread. Return to all comments →
My Java 8 Solution
public static void topView(Node root) { if (root == null) { return; } class Pair { Node node; int hd; Pair(Node n, int h) { node = n; hd = h; } } Map<Integer, Integer> topViewMap = new TreeMap<>(); Queue<Pair> queue = new LinkedList<>(); queue.add(new Pair(root, 0)); while (!queue.isEmpty()) { Pair current = queue.poll(); Node currentNode = current.node; int hd = current.hd; if (!topViewMap.containsKey(hd)) { topViewMap.put(hd, currentNode.data); } if (currentNode.left != null) { queue.add(new Pair(currentNode.left, hd - 1)); } if (currentNode.right != null) { queue.add(new Pair(currentNode.right, hd + 1)); } } for (int value : topViewMap.values()) { System.out.print(value + " "); } }
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 →
My Java 8 Solution