Clean python BFS

  • 0
    class Solution(object):
        def verticalOrder(self, root):
            if not root:
                return []
            from collections import defaultdict
            mem = defaultdict(list)
            queue = [(root,0)]
            while queue:
                node, position = queue.pop(0)
                if node.left:
                    queue.append((node.left, position-1))
                if node.right:
                    queue.append((node.right, position+1))
            return [mem[node] for node in sorted(mem)]

Log in to reply

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