Binary Tree Vertical Order Traversal

Medium

Topics
Hash TableTreeBinary TreeBFSSorting

Given the root of a binary tree, return the vertical order traversal of its node values.

Assign the root column 0. A left child sits one column to the left of its parent, a right child one column to the right. Group the nodes by column and return the groups ordered from the leftmost column to the rightmost.

Within a column, nodes appear top to bottom, and two nodes on the same row appear left to right.

On this judge the columns are shown separated by |.

Example 1

9col -13col 015col 020col +17col +2
nodes sharing a column
The root is column 0; a left child sits one column to its parent’s left and a right child one to its right, so the label beside each node is just that count applied. The shaded nodes land in the same column despite coming from different parts of the tree, and they come out top row first, then left to right within a row. Reading the columns from leftmost to rightmost gives [[9],[3,15],[20],[7]].
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation: Column -1 holds 9; column 0 holds 3 and, one row down, 15; column 1 holds 20; column 2 holds 7.

Example 2

4col -29col -10col 03col 01col 08col +17col +2
nodes sharing a column
Input:  root = [3,9,8,4,0,1,7]
Output: [[4],[9],[3,0,1],[8],[7]]
Explanation: Three nodes land in column 0: the root, plus 0 and 1 which come back in from opposite sides.

Example 3

1col 0
No two nodes share a column in this tree, so the grouping is one node per column.
Input:  root = [1]
Output: [[1]]
Explanation: A single node occupies column 0 alone.

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

The column of a node is fully determined by the path taken to reach it: start at 0, subtract one for every left step, add one for every right step. So the column can be carried down with the node, and no geometry has to be reconstructed afterwards.

The ordering rule is the part that catches people out. Two different columns can send nodes back into the same column — in example 2 the root, the right child of 9, and the left child of 8 all land in column 0 — and they must come out top-to-bottom, then left-to-right.

A breadth-first walk delivers exactly that order for free: it visits row by row, and within a row left to right. Appending to each column’s bucket as nodes are visited therefore fills every bucket in the required order, with no sorting of nodes needed. Only the columns have to be sorted at the end.

Approach

  1. Walk the tree breadth-first, carrying each node’s column alongside it. Push the root with column 0.
  2. Append every visited node’s value to the bucket for its column.
  3. Enqueue the left child at column - 1 and the right child at column + 1.
  4. When the walk finishes, read the buckets out in increasing column order.

Walkthrough

root = [3,9,20,null,null,15,7]

        3        col 0
       / \
      9   20     col -1, col 1
         /  \
        15   7   col 0, col 2

visit order (breadth-first) and the bucket each lands in
  3  -> col  0   buckets: {0: [3]}
  9  -> col -1   buckets: {-1: [9], 0: [3]}
  20 -> col  1   buckets: {-1: [9], 0: [3], 1: [20]}
  15 -> col  0   buckets: {-1: [9], 0: [3,15], 1: [20]}
  7  -> col  2   buckets: {-1: [9], 0: [3,15], 1: [20], 2: [7]}

columns in order -1, 0, 1, 2
answer [[9],[3,15],[20],[7]]

Complexity

  • Time — O(n log n): each node is visited once; the log factor is sorting the distinct column keys, of which there are at most n.
  • Space — O(n): the queue plus one stored value per node across the buckets.

Common Pitfalls

  • Walking the tree depth-first and appending as you go. A depth-first walk reaches a deep left node before a shallow right one, so a column fed by both comes out in the wrong order — example 2’s middle column would read 3, 1, 0 instead of 3, 0, 1.
  • Sorting each column’s values. The order is positional, not numeric; sorting example 1’s middle column would give 3, 15 by luck and break on negative values.
  • Returning the buckets in insertion order rather than by column. Insertion order follows the traversal, so it starts at column 0 rather than the leftmost.
  • Forgetting the empty tree, which has no columns at all.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def verticalOrder(self, root):
        if not root:
            return []
        buckets = {}
        q = [(root, 0)]
        i = 0
        while i < len(q):
            node, col = q[i]
            i += 1
            buckets.setdefault(col, []).append(node.val)
            if node.left:
                q.append((node.left, col - 1))
            if node.right:
                q.append((node.right, col + 1))
        return [buckets[c] for c in sorted(buckets)]
SensAI
Beta
Tap the mic to stop voice mode