314. Binary Tree Vertical Order Traversal

5 min read

314. Binary Tree Vertical Order Traversal

Binary tree vertical order traversal is one of the most elegant tree-based problems that tests your understanding of breadth-first search, hash maps, and coordinate-based indexing. Think about it: if you have ever struggled with how to "flatten" a two-dimensional tree structure into vertically aligned columns, this problem is your gateway to mastering that concept. In this article, we will explore the problem statement, the intuition behind the solution, a step-by-step algorithm, a complete code implementation, complexity analysis, and frequently asked questions.

Problem Statement

Given the root of a binary tree, return the vertical order traversal of its nodes' values. On top of that, nodes that share the same column index should be grouped together, ordered from top to bottom. Day to day, each node is assigned a column index, where the root starts at column 0, its left child is at column -1, its right child at column +1, and so on recursively. If multiple nodes in the same row and column exist, they should be sorted from left to right Small thing, real impact. That's the whole idea..

Here's one way to look at it: consider the following tree:

      3
     / \
    9   20
       /  \
      15   7

The vertical order traversal would be:

  • Column -1: [9]
  • Column 0: [3, 15]
  • Column 1: [20]
  • Column 2: [7]

The final output is [[9], [3, 15], [20], [7]].

Intuition Behind the Solution

The key insight is that vertical order traversal is essentially a level-order traversal (BFS) with an added dimension: the column index. While a standard BFS processes nodes level by level, here we also track which vertical column each node belongs to Turns out it matters..

Think of the tree as being projected onto a vertical wall. But the root casts a shadow at position 0. Every time you move left, the shadow shifts one unit to the left (-1). Practically speaking, every time you move right, it shifts one unit to the right (+1). By recording these column positions during BFS, we naturally capture the top-to-bottom ordering because BFS processes nodes level by level.

Algorithm Design

The algorithm can be broken down into the following steps:

  1. Initialize a queue for BFS. Each entry in the queue should store both the node and its column index.
  2. Initialize a hash map (dictionary) where the key is the column index and the value is a list of node values in that column.
  3. Perform BFS starting from the root at column 0:
    • Dequeue a node and its column index.
    • Append the node's value to the list corresponding to that column in the hash map.
    • Enqueue the left child with column index - 1.
    • Enqueue the right child with column index + 1.
  4. Sort the hash map keys (column indices) in ascending order.
  5. Return the values in the order of sorted column indices.

Step-by-Step Walkthrough

Let us trace through the example tree to see how this works in practice It's one of those things that adds up..

Initial state:

  • Queue: [(3, 0)]
  • Hash map: {}

Step 1: Dequeue (3, 0). Add 3 to column 0.

  • Queue: [(9, -1), (20, 1)]
  • Hash map: {0: [3]}

Step 2: Dequeue (9, -1). Add 9 to column -1 It's one of those things that adds up..

  • Queue: [(20, 1)]
  • Hash map: {-1: [9], 0: [3]}

Step 3: Dequeue (20, 1). Add 20 to column 1.

  • Queue: [(15, 0), (7, 2)]
  • Hash map: {-1: [9], 0: [3], 1: [20]}

Step 4: Dequeue (15, 0). Add 15 to column 0 Most people skip this — try not to..

  • Queue: [(7, 2)]
  • Hash map: {-1: [9], 0: [3, 15], 1: [20]}

Step 5: Dequeue (7, 2). Add 7 to column 2 It's one of those things that adds up..

  • Queue: []
  • Hash map: {-1: [9], 0: [3, 15], 1: [20], 2: [7]}

Final result: Sort columns: -1, 0, 1, 2 → [[9], [3, 15], [20], [7]]

Code Implementation

Here is a clean Python implementation using collections.defaultdict and collections.deque:

from collections import defaultdict, deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.

def verticalOrder(root):
    if not root:
        return []

    column_table = defaultdict(list)
    queue = deque([(root, 0)])

    while queue:
        node, column = queue.popleft()
        if node is not None:
            column_table[column].And append(node. append((node.left, column - 1))
            queue.val)
            queue.append((node.

    sorted_columns = sorted(column_table.keys())
    return [column_table[col] for col in sorted_columns]

The use of defaultdict(list) eliminates the need to check whether a column key already exists before appending. The deque ensures O(1) pops from the left, which is critical for maintaining BFS efficiency.

Complexity Analysis

  • Time Complexity: O(N log N) in the worst case, where N is the number of nodes. The BFS itself is O(N), but sorting the column keys takes O(C log C), where C is the number of distinct columns. In the worst case, C can be O(N), giving O(N log N) overall. If you use an ordered map or track min/max column indices, you can reduce this to O(N).
  • Space Complexity: O(N) to store the hash map and the queue. In the worst case, the queue holds all nodes at the widest level, which can be up to N/2 for a complete binary tree.

Important Considerations

One subtle point that often trips people up is the difference between vertical order traversal and vertical level traversal. Still, in vertical order traversal, nodes within the same column are ordered by their row (level), which BFS naturally guarantees. Even so, if you use DFS instead of BFS, you must also track the row index and sort by row within each column, which adds complexity.

You'll probably want to bookmark this section.

Another consideration is handling negative column indices. Since Python dictionaries support negative keys natively, this is not an issue in Python, but in languages with array-based maps, you would need to offset indices by the minimum column value.

Comparison with Similar Problems

Problem 314 is closely related to Leet

New In

Hot and Fresh

Readers Went Here

Follow the Thread

Thank you for reading about 314. Binary Tree Vertical Order Traversal. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home