• + 0 comments

    1 case failed, can you spot the bug?

    Create the top_view method

    def top_view(root: BinaryTreeNode) -> None: if root is None: return

    # Dictionary to store the first node at each horizontal distance
    top_view_map = {}
    
    # List for level order traversal (acting as a queue)
    queue = [(root, 0)]  # (node, horizontal distance)
    
    while queue:
        # Pop the first element from the list
        node, hd = queue[0]  # Get the first element
        queue = queue[1:]    # Remove the first element
    
        # If this is the first time we are visiting this horizontal distance
        if hd not in top_view_map:
            top_view_map[hd] = node.value
    
        # Add left and right children to the queue with updated horizontal distances
        if node.left:
            queue.append((node.left, hd - 1))
        if node.right:
            queue.append((node.right, hd + 1))
    
    # Sort the horizontal distances and print the corresponding node values
    for hd in sorted(top_view_map.keys()):
        print(top_view_map[hd], end=" ")