Ctrl K

Tree Rows by Depth

Medium
You are given the root of a binary tree. Group the node values by level: the first list holds the root's value, the second holds its children, the third its grandchildren, and so on. Within a level, values go from left to right, the way the nodes appear when the tree is drawn. Return the levels from top to bottom. If the tree is empty, return an empty list.
Example 1
root=tree_node([8, 4, -1, None, 6, 2]) → [[8], [4, -1], [6, 2]]

Depth 0 holds only the root 8, depth 1 holds 4 and -1, depth 2 holds the right child of 4 (6) and the left child of -1 (2), left to right.

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

The tree is a chain going right, so each level has a single node.

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

An empty tree gives an empty list.

Constraints
  • 0 ≤ number of nodes ≤ 2000
  • -1000 ≤ Node.val ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSnake Through the Tree Levels MediumTree Levels From the Bottom Up MediumThe Tree Seen From the Right MediumTree Columns, Top Down MediumFirst Value on the Lowest Row Medium
loading Python…
Input
root=tree_node([8, 4, -1, None, 6, 2])
Expected
[[8], [4, -1], [6, 2]]

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