Skip to problem
←

Vertical Order Traversal of a Binary Tree

Hard 0 attempts

Return the vertical traversal of a binary tree. Assign the root position (row, column) = (0, 0). A left child is at (row + 1, column - 1) and a right child is at (row + 1, column + 1).

Group values by column and return those groups from left to right. Within each column, order nodes by:

  1. Row, from top to bottom.
  2. Value, from smallest to largest, only when the row is also equal.

Keep duplicate values: each node appears once. Both the order of columns and the order within a column matter. The editor passes a root node with val, left, and right properties; displayed arrays use level order with null for missing children.

For [1,2,3,4,6,5,7], the middle column illustrates the tie rule:

Node value Row Column
1 0 0
6 2 0
5 2 0

That column is [1,5,6]: the root stays first, and the two row-2 values are sorted numerically, even though a left-first traversal encounters 6 before 5.

Function contract

Implement verticalTraversal(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return arrays of node values grouped by column, ordered by column, then row, then value. Both the outer and inner array order matter.

Example 1

Input
root = [3,9,20,null,null,15,7]
Output
[[9],[3,15],[20],[7]]

Example 2

Input
root = [1]
Output
[[1]]

Example 3

Input
root = [1,2,3,4,6,5,7]
Output
[[4],[2],[1,5,6],[3],[7]]
Constraints
  • 1 <= number of nodes <= 1000
  • 0 <= Node.val <= 1000

DFS with coordinate sorting

Record each node as [column, row, value]. Sort these triples lexicographically by numeric column, row, then value. This preserves top-to-bottom priority while resolving only same-position ties by value.

Walk the sorted triples and start a new output group whenever the column changes. No deduplication is needed: equal-valued nodes are still separate entries.

javascript
function verticalTraversal(root) {
  const nodes = [];
  function dfs(node, row, col) {
    if (!node) return;
    nodes.push([col, row, node.val]);
    dfs(node.left, row+1, col-1);
    dfs(node.right, row+1, col+1);
  }
  dfs(root, 0, 0);
  nodes.sort((a,b) => a[0]-b[0] || a[1]-b[1] || a[2]-b[2]);
  const result = []; let prevCol = -Infinity;
  for (const [col,,val] of nodes) {
    if (col !== prevCol) { result.push([]); prevCol = col; }
    result[result.length-1].push(val);
  }
  return result;
}

Time: O(n log n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript