Binary Tree Vertical Order Traversal

Medium Trees

root is the root of a binary tree, which may be empty. Every node has a column and a row: the root is in column 0 and row 0; a left child is one column to the left of its parent and a right child one column to the right; either child is one row below its parent.

List the columns from left to right, the smallest column number first. Within a column, list the nodes from top to bottom, the smallest row number first. Two nodes in the same column and the same row go in the order of a level-by-level walk that reads each row from left to right, so the one on the left goes first.

Return one list per column that holds a node: that column's values in this order, the lists in column order. An empty tree gives an empty list.

Example 1

Input: root = [6,3,8,1,4,7,9]
Output: [[1],[3],[6,4,7],[8],[9]]
6381479

Column 0 holds 6 in row 0, then 4 and 7, which share row 2. 4 is on the left, so it goes first.

Example 2

Input: root = [1,2,5,null,3,null,null,null,4]
Output: [[2],[1,3],[5,4]]
12534

Example 3

Input: root = [8,null,4,6]
Output: [[8,6],[4]]
846

Constraints

  • 0 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹
  • values may repeat

More Trees

All Trees problems