Description

987. Vertical Order Traversal of a Binary Tree

Given the root of a binary tree, calculate the vertical order traversal of the binary tree.

For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively. The root of the tree is at (0, 0).

The vertical order traversal of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.

Return the vertical order traversal of the binary tree.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[9],[3,15],[20],[7]]
Explanation:
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.

Example 2:

Input: root = [1,2,3,4,5,6,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
1 is at the top, so it comes first.
5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.

Example 3:

Input: root = [1,2,3,4,6,5,7]
Output: [[4],[2],[1,5,6],[3],[7]]
Explanation:
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.

Constraints:

  • The number of nodes in the tree is in the range [1, 1000].
  • 0 <= Node.val <= 1000

Approach 1: BFS with Custom Coordinate Sorting ( Time, Space)

Intuition

  1. Perform a Breadth-First Search (BFS) using a Queue (ArrayDeque) to traverse the tree and collect (col, row, val) for every node, starting from root at (0, 0).
  2. Save each node’s tuple into a list.
  3. Sort the tuples using a multi-level comparator:
    • Primary: col ascending (leftmost to rightmost).
    • Secondary: row ascending (top to bottom).
    • Tertiary: val ascending (if two nodes share the exact same row and col).
  4. Iterate through the sorted list and group values by col.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
 
class Solution {
    private static class Element {
        int col, row, val;
        Element(int col, int row, int val) {
            this.col = col;
            this.row = row;
            this.val = val;
        }
    }
 
    private static class QueueNode {
        TreeNode node;
        int col, row;
        QueueNode(TreeNode node, int col, int row) {
            this.node = node;
            this.col = col;
            this.row = row;
        }
    }
 
    public List<List<Integer>> verticalTraversal(TreeNode root) {
        List<Element> elements = new ArrayList<>();
        if (root == null) return new ArrayList<>();
 
        Deque<QueueNode> queue = new ArrayDeque<>();
        queue.offer(new QueueNode(root, 0, 0));
 
        while (!queue.isEmpty()) {
            QueueNode curr = queue.poll();
            elements.add(new Element(curr.col, curr.row, curr.node.val));
 
            if (curr.node.left != null) {
                queue.offer(new QueueNode(curr.node.left, curr.col - 1, curr.row + 1));
            }
            if (curr.node.right != null) {
                queue.offer(new QueueNode(curr.node.right, curr.col + 1, curr.row + 1));
            }
        }
 
        // Sort by col -> row -> val
        Collections.sort(elements, (a, b) -> {
            if (a.col != b.col) return Integer.compare(a.col, b.col);
            if (a.row != b.row) return Integer.compare(a.row, b.row);
            return Integer.compare(a.val, b.val);
        });
 
        // Group elements by column
        List<List<Integer>> result = new ArrayList<>();
        int i = 0;
        while (i < elements.size()) {
            List<Integer> colList = new ArrayList<>();
            int currCol = elements.get(i).col;
            while (i < elements.size() && elements.get(i).col == currCol) {
                colList.add(elements.get(i).val);
                i++;
            }
            result.add(colList);
        }
 
        return result;
    }
}
 

Complexity

  • Time Complexity: — BFS takes time, and sorting elements takes time.
  • Space Complexity: — Auxiliary space for the BFS queue, element list, and final result lists.

Approach 2: DFS with Nested TreeMap and PriorityQueue ( Time, Space)

Intuition

  1. Use Depth-First Search (DFS) tracking (col, row) coordinates.
  2. Store nodes in a nested map structure: TreeMap<Integer, PriorityQueue<Integer TreeMap<Integer,>>>:
    • Outer TreeMap: key is col (automatically keeps columns sorted left-to-right).
    • Inner TreeMap: key is row (automatically keeps rows sorted top-to-bottom).
    • Value: PriorityQueue<Integer> (min-heap that automatically keeps node values sorted for identical (col, row) coordinates).
  3. Traverse the nested map values to construct the final output.
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.TreeMap;
 
class Solution {
    public List<List<Integer>> verticalTraversal(TreeNode root) {
        // Map: col -> (row -> PriorityQueue of node values)
        TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map = new TreeMap<>();
        dfs(root, 0, 0, map);
 
        List<List<Integer>> result = new ArrayList<>();
        for (TreeMap<Integer, PriorityQueue<Integer>> rows : map.values()) {
            List<Integer> colList = new ArrayList<>();
            for (PriorityQueue<Integer> pq : rows.values()) {
                while (!pq.isEmpty()) {
                    colList.add(pq.poll());
                }
            }
            result.add(colList);
        }
 
        return result;
    }
 
    private void dfs(TreeNode node, int col, int row, TreeMap<Integer, TreeMap<Integer, PriorityQueue<Integer>>> map) {
        if (node == null) return;
 
        map.putIfAbsent(col, new TreeMap<>());
        map.get(col).putIfAbsent(row, new PriorityQueue<>());
        map.get(col).get(row).offer(node.val);
 
        dfs(node.left, col - 1, row + 1, map);
        dfs(node.right, col + 1, row + 1, map);
    }
}
 

Complexity

  • Time Complexity: — Each node insertion into TreeMap and PriorityQueue takes time.
  • Space Complexity: — Auxiliary space for the nested TreeMap and call stack.

Easy Memory Rule

“Track (col, row) for every node Sort by col first, then row, then val (for overlaps)!”