Clean Python solution using dictionary of dictionary


  • 0
    K
    def verticalOrder(self, root):
        d = collections.defaultdict(lambda: collections.defaultdict(list))
        self.helper(root, 0, 0, d)
        res = []
        for k in sorted(d.keys()):
            res.append([])
            for j in sorted(d[k].keys()):
                res[-1].extend(d[k][j])
        return res
        
    def helper(self, root, horizontal_lvl, vertical_lvl, d):
        if not root:
            return
        d[horizontal_lvl][vertical_lvl].append(root.val)
        self.helper(root.left, horizontal_lvl-1, vertical_lvl+1, d)
        self.helper(root.right, horizontal_lvl+1, vertical_lvl+1, d)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.