• + 1 comment

    THIS QUESTION IS SO F BAD. It's not like it's hard but the problem is so poorly explained and the test cases are so illy created.

    I at first thought it's just all the left most nodes and right most nodes are visible from top view, it also satisifies the test case presented and fit the problem difficulty. But no, so I had to search up the definition of top view which turns out is horizontal distance corresponds to the node parent. Thats also bearable, just need to keep track of parent distance and visited distance, not too bad.

    BUT HOW CAN YOU NOT ALLOW DIFFERENT PERMUTATION OF THE ANSWER?!

    so i had to guess it's sorted by the distance and store them in hashmap... sigh

    def topView(root):
        dst_hm = {}
        frontier = [(root, 0)]
        while frontier:
            nxt = []
            for v in frontier:
                if v[1] not in dst_hm:
                    # print(v[0].info, end=' ')
                    dst_hm[v[1]] = (v[0])
                    
                if v[0].left:
                    nxt.append((v[0].left, v[1]-1))
                if v[0].right:
                    nxt.append((v[0].right, v[1]+1))
            frontier = nxt
        
        for ele in sorted(dst_hm.keys()):
            print(dst_hm[ele], end=' ')