Easy to understand python solution


  • 0
    Y
    class Solution(object):
    def verticalOrder(self, root):
        if not root: return []
        
        d = {}
        queue = [(root, 0)]
    
        # index denotes which column the node is in
        while queue:
            curNode, index = queue.pop(0)
            d[i] = d.get(i, []) + [curNode.val]
            if curNode.left: queue.append((curNode.left, index-1))
            if curNode.right: queue.append((curNode.right, index+1))
        
        minIndex = min(d.keys())
        maxIndex = max(d.keys())
        
        res = []
        for i in range(minIndex, maxIndex+1):
            res.append(d[i])
        return res

Log in to reply
 

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