Ctrl K

Tree Columns, Top Down

Medium
You are given the root of a binary tree. Draw the tree on grid paper: the root is in column 0, the left child of any node is one column to the left of it, and the right child is one column to the right. Return the node values column by column, from the leftmost column to the rightmost. Within a column, nodes go from top to bottom; if two nodes of a column are at the same depth, the one further left in the drawing comes first (that is, the one met earlier when a level is scanned from left to right). For an empty tree, return an empty list.
Example 1
root=tree_node([6, 4, 8, 1, 5, 7, 9]) → [[1], [4], [6, 5, 7], [8], [9]]

The root is in column 0, while 4 and 8 sit in columns -1 and 1. Nodes 5 and 7 both land in column 0 at the same depth, so they go left to right: 6, 5, 7.

Example 2
root=tree_node([2, None, 3, 1]) → [[2, 1], [3]]

3 is in column 1, and its left child 1 moves back into column 0 under the root.

Example 3
root=tree_node([]) → []

An empty tree has no columns.

Constraints
  • 0 ≤ number of nodes ≤ 1000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Columns With Ties HardSmallest Cover of the Bottom Row MediumWhere the Deepest Leaves Meet MediumHops Between Two Keys MediumSpread Through the Tree Medium
loading Python…
Input
root=tree_node([6, 4, 8, 1, 5, 7, 9])
Expected
[[1], [4], [6, 5, 7], [8], [9]]

Run checks the first 3 tests in your browser. Submit checks all 89 tests on the server, hidden ones included.