Ctrl K

Tree Levels From the Bottom Up

Medium
You are given the root of a binary tree. Group the node values by level (nodes at the same depth) and return the levels starting from the deepest one and ending with the root's level. Within a level, values go from left to right, the way the nodes appear when the tree is drawn. For an empty tree, return an empty list.
Example 1
root=tree_node([4, 8, -2, None, 5, 1]) → [[5, 1], [8, -2], [4]]

The lowest level holds 5 (right child of 8) and 1 (left child of -2), above it are 8 and -2, and at the top is the root 4.

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

First the only leaf 3, then the root 7.

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

An empty tree has no levels.

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 problemsTree Rows by Depth MediumSnake Through the Tree Levels MediumThe Tree Seen From the Right MediumTree Columns, Top Down MediumFirst Value on the Lowest Row Medium
loading Python…
Input
root=tree_node([4, 8, -2, None, 5, 1])
Expected
[[5, 1], [8, -2], [4]]

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