Facebook | Phone interview | SWE intern
Anonymous User
771

Prompt
This was the same prompt as Vertical Order Traversal, except without the stipulation that nodes in the same position must be sorted by value.

Level Order Traversal Solution

def verticalTraversal(root):
    # Level-order traversal, keeping track of xpos
    q = deque([(root, 0)])
    # Record columns
    # Key is xpos of col
    # Val is list of vals in that col, sorted from top to bottom
    cols = defaultdict(list)
    while q:
        n = len(q)
        for i in range(n):
            node, x = q.popleft()
            cols[x].append(node.val)
            # Append children to queue, with their xpos
            if node.left:
                q.append((node.left, x - 1))
            if node.right:
                q.append((node.right, x + 1))
    # Format answer
    ans = [cols[x] for x in sorted(cols.keys())]
    return ans
Comments (1)