Algo-Sim › Binary Trees & BST

Vertical Order Traversal of a Binary Tree

Hard · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Give each node (column, row) coordinates, sort by column, row and value, then group the sorted list by column.

Problem

The root of a binary tree is at column 0, row 0; a node’s left child is one column left and one row down, its right child one column right and one row down. Return the values column by column from left to right, each column top to bottom, with nodes in the same row and column ordered by value.

Constraints

Edge cases to test

Follow-up questions

Why sort on three keys?
The task orders by column, then row, then value; that tie-break is what separates LC 987 from LC 314.
What is the cost?
O(n log n) for the sort. Without the value tie-break, BFS by column with a min/max column range is O(n).

Solution

Java

public List<List<Integer>> verticalTraversal(TreeNode root) {
    List<int[]> cells = new ArrayList<>();
    place(root, 0, 0, cells);
    // Left to right by column, then top to bottom, then the smaller value.
    cells.sort((a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] != b[1] ? a[1] - b[1] : a[2] - b[2]);
    List<List<Integer>> columns = new ArrayList<>();
    int last = Integer.MIN_VALUE;
    for (int[] c : cells) {
        if (c[0] != last) {
            columns.add(new ArrayList<>());
            last = c[0];
        }
        columns.get(columns.size() - 1).add(c[2]);
    }
    return columns;
}

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

Python

def vertical_traversal(root):
    cells = []
    place(root, 0, 0, cells)
    # Left to right by column, then top to bottom, then the smaller value.
    cells.sort()
    columns, last = [], None
    for col, row, val in cells:
        if col != last:
            columns.append([])
            last = col
        columns[-1].append(val)
    return columns


def place(node, col, row, cells):
    if not node:
        return
    cells.append((col, row, node.val))
    place(node.left, col - 1, row + 1, cells)
    place(node.right, col + 1, row + 1, cells)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<vector<int>> verticalTraversal(TreeNode *root) {
        vector<array<int, 3>> cells;
        place(root, 0, 0, cells);
        // Left to right by column, then top to bottom, then the smaller value.
        sort(cells.begin(), cells.end());
        vector<vector<int>> columns;
        int last = INT_MIN;
        for (auto &c : cells) {
            if (c[0] != last) {
                columns.push_back({});
                last = c[0];
            }
            columns.back().push_back(c[2]);
        }
        return columns;
    }

  private:
    void place(TreeNode *node, int col, int row, vector<array<int, 3>> &cells) {
        if (node == nullptr)
            return;
        cells.push_back({col, row, node->val});
        place(node->left, col - 1, row + 1, cells);
        place(node->right, col + 1, row + 1, cells);
    }
};

More Binary Trees & BST problems