Vertical Order Traversal of a Binary Tree

Hard

Topics
Hash TableTreeDFSBFSSortingBinary Tree

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

Within a column, nodes come top row first. Where two nodes share both a column and a row, they come out in increasing order of value — this is the one difference from the simpler vertical-order problem, which takes them left to right instead.

On this judge the columns are shown separated by |.

Example 1

tree9-13015020+17+2
column -19
column 0315
column +120
column +27
nodes of one column
Every node sits in a column: the root is column 0, a left child one column to the left of its parent and a right child one to the right. The small number above each node is that column, and the lower rows are the answer, one row per column from leftmost to rightmost. Inside a column the higher node comes first; no two nodes share a row and column here, so the value tie-break never applies.
Columns are counted by horizontal offset, not by depth, so distant nodes can share one.
Input:  root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation: No two nodes share a row and a column here, so the ordering rule never comes up.

Example 2

tree4-22-15010603+17+2
column -24
column -12
column 0156
column +13
column +27
nodes of one column
Inside a column the higher node comes first, and where two share a row they are ordered by value, which is the case that makes the answer unique here.
Input:  root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation: Nodes 5 and 6 share column 0 and row 2. They are reported 5 then 6 by value — and 6 sits to the left of 5 in the drawing, so left-to-right would give the other order.

Example 3

tree10
column 01
nodes of one column
Input:  root = [1]
Output: [[1]]
Explanation: One node in column 0.

Constraints

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

Intuition

The column of a node follows from the path to it — start at 0, subtract one per left step, add one per right — so it can be carried down during a traversal and needs no reconstruction.

The twist is the tie-break, and it is worth seeing why it is awkward. A breadth-first walk delivers nodes in row order and, within a row, left to right — which is exactly the ordering the other vertical-order problem wants. Here a row-and-column collision is broken by value instead, and traversal order cannot supply that: in example 2 the node with the smaller value sits to the right.

So the traversal can establish the column and the row, and the ordering has to be imposed afterwards. Collect (column, row, value) for every node and sort by all three; the groups then fall out by column.

That is why this problem is graded harder than its sibling despite looking almost identical: the answer is a sort, not a walk.

Approach

  1. Walk the tree in any order, carrying each node’s column and row. Record a triple (column, row, value) for each.
  2. Sort the triples by column, then row, then value.
  3. Group consecutive triples that share a column, emitting the values in sorted order.
  4. Return the groups in increasing column order.

Walkthrough

root = [1,2,3,4,5,6,7]

          1        col 0, row 0
        /   \
       2     3      col -1 and +1, row 1
      / \   / \
     4   5 6   7    col -2, 0, 0, +2, row 2

triples (column, row, value)
   (-2, 2, 4) (-1, 1, 2) (0, 0, 1) (0, 2, 5) (0, 2, 6)
   (1, 1, 3) (2, 2, 7)

sorted by column, then row, then value -- the two column-0
row-2 entries order as 5 then 6 by VALUE

groups
   col -2: [4]
   col -1: [2]
   col  0: [1, 5, 6]
   col  1: [3]
   col  2: [7]

In the drawing 6 is to the left of 5, so a left-to-right rule
would emit [1, 6, 5] here.

Complexity

  • Time — O(n log n): the traversal is linear and the sort dominates. The sort is unavoidable because the ordering is by value, which no traversal order provides.
  • Space — O(n): one triple per node, which dominates. The DFS also costs a call stack of O(h) frames, where h is the tree height — O(log n) when balanced and O(n) on a degenerate one-child-per-level tree, so the worst case is the same O(n) either way.

Common Pitfalls

  • Breaking a row-and-column tie by traversal order. That is the sibling problem’s rule, and example 2 distinguishes them.
  • Sorting by column and value but not row. Row has to come second, or a deep small value jumps above a shallow large one.
  • Grouping by column during the traversal and sorting each group afterwards. Sorting the values alone loses the row, so a deep small value again sorts to the top.
  • Forgetting that columns can be negative, and indexing an array by column directly.

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 verticalTraversal(self, root):
        triples = []

        def walk(node, column, row):
            if not node:
                return
            triples.append((column, row, node.val))
            walk(node.left, column - 1, row + 1)
            walk(node.right, column + 1, row + 1)

        walk(root, 0, 0)
        triples.sort()

        out = []
        for column, _row, value in triples:
            if out and out[-1][0] == column:
                out[-1][1].append(value)
            else:
                out.append((column, [value]))
        return [values for _column, values in out]
SensAI
Beta
Tap the mic to stop voice mode