Python Simple BFS Solution


  • 2
    G
    def verticalOrder(root):
        nodes = collections.defaultdict(list)
        queue = collections.deque([(root, 0)])
        while queue:
            node, pos = queue.popleft()
            if not node:
                continue
            nodes[pos].append(node.val)
            queue.append((node.left, pos-1))
            queue.append((node.right, pos+1))
        return [nodes[i] for i in sorted(nodes)]

Log in to reply
 

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