• + 0 comments

    I try to find a better definition of top view since the one presented is terrible: the list nodes, from left to the right, that projected vertically from the top to the bottom, are NOT covered by other nodes.

    # layer: meant as horizontal layer, integer
    #    < 0 (left of the root) or > 0 (right of the root)
    # depth: depth in the three from zero, always positive
    
    def explore(node, results, layer: int = 0, depth : int = 0):
        if layer not in results:
            # if it a new layer, no matter of the current depth
            results[layer] = { 'depth': depth, 'content': node.info }
        else:
            # there was already a node on this layer
            if depth < results[layer].get('depth'):
                results[layer] = { 'depth': depth, 'content': node.info }
        
        if node.left is not None:
            explore(node.left, results, layer-1, depth+1)
           
        if node.right is not None:
            explore(node.right, results, layer+1, depth+1)
        
    def topView(root):
        #Write your code here
        results = {}
        explore(root, results)
    
        min_index = min(results.keys())
        max_index = max(results.keys())
        for i in range(min_index, max_index+1):
            print(results[i].get('content'), end=" ")