Vertical Order Traversal of a Binary Tree

Pattern: Views and boundaries

hard

Give each node (column, row): left child (c - 1, r + 1), right child (c + 1, r + 1). Sort all nodes by column, then row, then value, and group them by column.

The problem

Return the vertical order: columns from left to right, each from top to bottom; nodes in the same row and column are sorted by value. [3, 9, 20, null, null, 15, 7] gives [[9], [3, 15], [20], [7]]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What two numbers place a node?
  • In what order must nodes in one column appear?
  • When do values decide?

Hints

    Brute force, and why it fails

    BFS by column with a map of lists, sorting only the ties: also fine.

    The key insight

    With (column, row, value) for every node, one sort puts everything in the required order.

    Dry run

    nodes5

    Tree [3, 9, 20, null, null, 15, 7]. Positions: 3 (0, 0), 9 (-1, 1), 20 (1, 1), 15 (0, 2), 7 (2, 2).

    Step 1 of 3

    The plan

    collect (col, row, val) for every node
    sort
    group consecutive entries by col
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    One traversal and one sort.

    Edge cases

    • Ties in both column and row: sorted by value.
    • One node.
    • A chain: one column per node.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> verticalTraversal(TreeNode root) {
            List<int[]> nodes = new ArrayList<>();  // {column, row, value}
            collect(root, 0, 0, nodes);
            nodes.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] != b[1] ? a[1] - b[1] : a[2] - b[2]);   // column, row, value
            List<List<Integer>> out = new ArrayList<>();
            for (int i = 0; i < nodes.size(); i++) {
                if (i == 0 || nodes.get(i)[0] != nodes.get(i - 1)[0]) out.add(new ArrayList<>());   // a new column
                out.get(out.size() - 1).add(nodes.get(i)[2]);
            }
            return out;
        }
    
        private void collect(TreeNode n, int col, int row, List<int[]> nodes) {
            if (n == null) return;
            nodes.add(new int[]{col, row, n.val});
            collect(n.left, col - 1, row + 1, nodes);
            collect(n.right, col + 1, row + 1, nodes);
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> verticalTraversal(TreeNode* root) {
            vector<vector<int>> nodes;              // {column, row, value}
            collect(root, 0, 0, nodes);
            sort(nodes.begin(), nodes.end());       // column, then row, then value
            vector<vector<int>> out;
            for (size_t i = 0; i < nodes.size(); i++) {
                if (i == 0 || nodes[i][0] != nodes[i - 1][0]) out.push_back(vector<int>());   // a new column
                out.back().push_back(nodes[i][2]);
            }
            return out;
        }
    
        void collect(TreeNode* n, int col, int row, vector<vector<int>>& nodes) {
            if (n == NULL) return;
            nodes.push_back(vector<int>{col, row, n->val});
            collect(n->left, col - 1, row + 1, nodes);
            collect(n->right, col + 1, row + 1, nodes);
        }
    };

    Python

    class Solution:
        def verticalTraversal(self, root) -> list[list[int]]:
            nodes = []                              # (column, row, value)
    
            def collect(n, col, row):
                if n:
                    nodes.append((col, row, n.val))
                    collect(n.left, col - 1, row + 1)
                    collect(n.right, col + 1, row + 1)
    
            collect(root, 0, 0)
            out = []
            for i, (col, _, val) in enumerate(sorted(nodes)):   # column, then row, then value
                if i == 0 or col != prev:
                    out.append([])                  # a new column
                out[-1].append(val)
                prev = col
            return out

    Common mistakes

    • Sorting by value before row.
    • Using level order without breaking ties by value.

    Similar problems