class Node { constructor(public data: number, public left: Node | null = null, public right: Node | null = null) {} } function topView(root: Node | null): number[] { if (!root) return []; const map = new Map<number, number>(); const queue: Array<{node: Node; hd: number}> = [{node: root, hd: 0}]; let minHd = 0, maxHd = 0; while (queue.length > 0) { const {node, hd} = queue.shift()!; if (!map.has(hd)) { map.set(hd, node.data); } if (node.left) queue.push({node: node.left, hd: hd - 1}); if (node.right) queue.push({node: node.right, hd: hd + 1}); minHd = Math.min(minHd, hd); maxHd = Math.max(maxHd, hd); } const result = []; for (let i = minHd; i <= maxHd; i++) { result.push(map.get(i)!); } return result; } // Tree structure: // 1 // / \ // 2 3 // \ \ // 4 5 const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.right = new Node(4); root.right.right = new Node(5); console.log(topView(root));
The top view shows the nodes visible when the tree is viewed from above. We track horizontal distances (hd) from the root (hd=0). For each hd, the first node encountered in level order traversal is included.
Here, nodes at hd -1 is 2, hd 0 is 1, hd 1 is 3, and hd 2 is 5. Node 4 is at hd 0 but appears after 1, so it is not included.
Horizontal distance is a measure of how far left or right a node is from the root node. The root has hd = 0. Moving left decreases hd by 1, moving right increases hd by 1.
The code uses queue.pop() which removes the last element, making the traversal depth-first instead of breadth-first. This causes nodes to be processed in the wrong order, so the first node at each horizontal distance may be missed, resulting in an incomplete or empty map.
Horizontal distances: 10 (0), 5 (-1), 15 (1), 3 (-2), 7 (0), 18 (2), 4 (-1), 16 (1).
First nodes at each hd: -2:3, -1:5, 0:10, 1:15, 2:18.
Nodes 4, 7, 16 are not first at their hd.
BFS visits nodes level by level, so the first node encountered at each horizontal distance is guaranteed to be the topmost node. DFS may visit deeper nodes first, missing the correct top view nodes.