To capture the top view of a binary tree, we need to traverse the tree while keeping track of horizontal distances (HD) and levels. For each HD, we only keep the first node encountered. This can be efficiently achieved using a level order traversal (Breadth-First Search) and a dictionary to store the first node at each horizontal distance.
classSolution:
deftopView(self, root: TreeNode) -> List[int]:
ifnot root:
return []
hd_node_map: Dict[int, int] = {}
queue: Deque[(TreeNode, int)] = deque([(root, 0)])
while queue:
node, hd = queue.popleft()
if hd notin hd_node_map:
hd_node_map[hd] = node.val
if node.left:
queue.append((node.left, hd -1))
if node.right:
queue.append((node.right, hd +1))
return [hd_node_map[hd] for hd in sorted(hd_node_map)]