• + 4 comments

    Yep this is true, we now have to worry about all nodes, not just one on the sides. Also you have to sort them by levels. This is my solution in Python.

    def topView(root):
        uniq_lvls = []
        q = Queue()
        q.put((root, 0))
        
        while not q.empty():
            temp = q.get()
            if temp[1] not in (i[1] for i in uniq_lvls):
                uniq_lvls.append(temp)
            if temp[0].left:
                q.put((temp[0].left, temp[1]-1))
            if temp[0].right:
                q.put((temp[0].right, temp[1]+1))
        for x in sorted(uniq_lvls, key=lambda e: e[1]):
            print(x[0].info, end=' ')
    

    I am open to your suggestions of how I can improve speed and particularly memory consumption.