Vertical Order Traversal of a Binary Tree

List the values of a binary tree column by column, top to bottom, with nodes in the same spot sorted by value.

Given the root of a binary tree, list its values column by column. The root sits at row 0, column 0. A node at row row and column col has its left child at row row + 1, column col - 1, and its right child at row row + 1, column col + 1.

Return one list per column, from the leftmost column to the rightmost. Inside a column, list the values from top to bottom. When two nodes share the same row and column, put the smaller value first.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[9], [3, 15], [20], [7]]
Example 2
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [[4], [2], [1, 5, 6], [3], [7]]
Explanation: 5 and 6 share row 2 and column 0, so they are sorted by value.
Solution

The Idea

Picture the tree drawn on squared paper. Every step down to a left child moves one square to the left, and every step down to a right child moves one square to the right. Now read the drawing one column at a time, from the left edge to the right edge, each column from top to bottom.

The input of Example 1, [3, 9, 20, null, null, 15, 7], lists the tree row by row. 3 is on top, then come its children 9 and 20. Then come the children of 9, which has none, so both are null, and finally the children of 20, which are 15 and 7.

On the paper, 3 is in column 0. Its left child 9 lands in column -1 and its right child 20 in column 1. From 20, the left child 15 steps back into column 0 and the right child 7 into column 2. So column 0 holds 3 at the top and 15 two rows below it, and the answer is [[9], [3, 15], [20], [7]].

Example 2 adds a twist. Look at the picture below.

The tree with nodes 1 to 7 laid out in columns -2 to 2 and rows 0 to 2. Nodes 5 and 6 share row 2, column 0. Reading each column from top to bottom gives [4], [2], [1, 5, 6], [3], [7].

Each shaded band is one column, from column -2 on the left to column 2 on the right. Node 5 is the right child of 2, so it steps from column -1 back into column 0. Node 6 is the left child of 3, so it steps from column 1 back into column 0 as well.

Both end up in row 2, column 0, in the same spot, as the orange label "5 and 6 share row 2, column 0" shows. Reading top to bottom cannot say which comes first, so the problem breaks the tie by value. That is why the row labelled "result" reads [1, 5, 6] under column 0.

How do we get the nodes out in this order? A walk down the tree does not visit them column by column. Starting at 1, it goes to 2 and then to 4, which belongs to a column further left than both. But each node's place in the answer depends on just three numbers: its column, its row and its value.

So write down those three numbers for every node, sort the list by column, then by row, then by value, and the nodes come out in exactly the order the answer lists them. All that is left is to cut the sorted list wherever the column changes.

Solution Approach

Turning that idea into code means settling three things: how each node gets its column and row, how to sort the nodes, and how to cut the sorted list into columns.

Giving each node its column and row

Where does a node's column and row come from? Only from its parent. So the walk starts at the root with column 0 and row 0, and hands each child its own numbers: col - 1 for the left child, col + 1 for the right, and row + 1 for both.

The order of the walk does not matter, because the sort decides the final order. Each node becomes a small record of three int values, {column, row, value}.

Sorting the records

How should two records compare? First by column, so left columns come first. If the columns are equal, by row, so higher nodes come first. If the rows are equal too, the two nodes share a spot, and the smaller value comes first.

Each comparison uses Integer.compare, which returns a negative number, zero or a positive number without subtracting the two values. Subtracting, as in a - b, can go past the range of an int when the values are far apart.

Another way is a map from column to its nodes, kept in column order. Each column then still needs sorting by row and value, so one sort of all the records is the simpler choice.

Cutting the sorted list into columns

How do we see where one column ends? After the sort, all records of a column sit next to each other. Walking through them, a record whose column differs from the one before it starts a new list in the answer.

Java Solution

The method verticalTraversal works in these steps:

  1. First, create nodes, a list of int arrays, and fill it with collect(root, 0, 0, nodes). collect stops at a missing child. Otherwise it adds the record {col, row, node.val}, then calls itself for the left child with col - 1 and for the right child with col + 1, both at row + 1.
  2. Sort nodes with nodes.sort and a comparator, the function that tells the sort which of two records comes first. It compares columns, then rows, then values, each with Integer.compare.
  3. Create result, the list of columns, and column, an Integer that starts as null, so the first record always opens a list. Then loop over the sorted records. When a record's column differs from column, add a new empty list to result and store the new column in column.
  4. Add the record's value to the last list in result. After the loop, return result.

The class also has a small TreeNode class and a build helper that makes a tree from the row-by-row form of the examples, with null for a missing child.

The main method runs both examples, Example 2 with 5 and 6 swapped, a path that zigzags back into column 0, a tree of one node and an empty tree.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class VerticalOrderTraversalOfBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<List<Integer>> verticalTraversal(TreeNode root) {
        List<int[]> nodes = new ArrayList<>();      // each entry: {column, row, value}
        collect(root, 0, 0, nodes);
        nodes.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])  // column: left first
                : a[1] != b[1] ? Integer.compare(a[1], b[1])             // row: top first
                : Integer.compare(a[2], b[2]));                          // same spot: by value
        List<List<Integer>> result = new ArrayList<>();
        Integer column = null;
        for (int[] n : nodes) {
            if (column == null || n[0] != column) {
                result.add(new ArrayList<>());      // a new column starts
                column = n[0];
            }
            result.get(result.size() - 1).add(n[2]);
        }
        return result;
    }

    private static void collect(TreeNode node, int col, int row, List<int[]> nodes) {
        if (node == null) {
            return;
        }
        nodes.add(new int[] {col, row, node.val});
        collect(node.left, col - 1, row + 1, nodes);
        collect(node.right, col + 1, row + 1, nodes);
    }

    // builds a tree from the row-by-row form, with null for a missing child
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = queue.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                queue.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                queue.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(verticalTraversal(build(3, 9, 20, null, null, 15, 7)));
        System.out.println(verticalTraversal(build(1, 2, 3, 4, 5, 6, 7)));
        System.out.println(verticalTraversal(build(1, 2, 3, 4, 6, 5, 7)));
        System.out.println(verticalTraversal(build(1, 2, null, null, 3, null, 4)));
        System.out.println(verticalTraversal(build(5)));
        System.out.println(verticalTraversal(build()));
    }
}

Running it prints:

Output
[[9], [3, 15], [20], [7]]
[[4], [2], [1, 5, 6], [3], [7]]
[[4], [2], [1, 5, 6], [3], [7]]
[[2], [1, 3], [4]]
[[5]]
[]

Look at the second and third lines: both read [1, 5, 6] for column 0. The third tree, [1, 2, 3, 4, 6, 5, 7], makes 6 the right child of 2 and 5 the left child of 3, so the walk records 6 before 5. The value comparison still puts 5 first.

That last comparison is easy to leave out. We ran the same program with a comparator that stops after the row, and that third line came out as [[4], [2], [1, 6, 5], [3], [7]]. List.sort keeps records that compare as equal in the order they were added, so 6 stays ahead of 5.

The fourth line, [[2], [1, 3], [4]], comes from the path 1, 2, 3, 4, which turns left once and then right twice. 2 lands in column -1, 3 steps back into column 0 two rows below the root, and 4 moves on to column 1. So column 0 reads [1, 3], with the deeper 3 after 1.

The last two lines show that a single node gives one column, [[5]], and an empty tree gives an empty list, [], because the loop has no records to go through.

Complexity

The work is one walk over the tree, one sort of the records and one pass over the sorted records.

  • Time: O(n log n), because sorting the n records, one for each node, takes O(n log n) comparisons, while the walk and the grouping loop each touch a record only once.
  • Space: O(n), because nodes keeps a three-number record for every node, and the recursion in collect goes as deep as the tree is tall, which is at most n calls.