Python solution using level order traversal


  • 1
    from collections import deque
    
    
    class Solution(object):
        def verticalOrder(self, root):
            queue, dic = deque([(root, 0, 0)]), collections.defaultdict(list)
            while queue:
                cur, idx, lev = queue.popleft()
                if not cur:
                    continue
                dic[idx] += cur.val,
                queue.append((cur.left, idx - 1, lev + 1))
                queue.append((cur.right, idx + 1, lev + 1))
            if dic:
                b, e, ret = min(dic.keys()), max(dic.keys()), []
                for i in range(b, e + 1):
                    ret.append(dic[i])
            return ret

  • 0

    Why the inner function? Is that a remainder of a recursive attempt?


  • 0

    Yes, lol. fixed.


Log in to reply
 

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