Binary Tree Level Order Traversal II Problem
Description
LeetCode Problem 107.
Given the root of a binary tree, return the bottom-up level order traversal of its nodes' values. (i.e., from left to right, level by level from leaf to root).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[15,7],[9,20],[3]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range [0, 2000].
- -1000 <= Node.val <= 1000
Solution
Approach: Breadth-First Search, Then Reverse
Reading a tree level by level is a breadth-first search. The bottom-up order only changes the final step: collect the levels top-down as usual, then reverse the list of levels.
Process the tree one level at a time:
- Start with
current = [root](return[]right away if the tree is empty). - While
currentis not empty, go through its nodes from left to right. Record each value inlevel, and add each node's existing children, left before right, tonext. - Append
levelto the answer and continue withcurrent = next. - At the end, reverse the list of levels.
Because children are added left before right and the nodes of a level are visited left to right, every level comes out in left-to-right order. Only the order of the levels is reversed, not the values inside a level: for [3,9,20,null,null,15,7] the levels are [3], [9,20], [15,7], and the answer is [[15,7],[9,20],[3]].
Reversing once at the end takes O(n) in total. Inserting each new level at the front of an array list instead would shift all earlier levels every time.
Complexity: O(n) time and O(n) space, where n is the number of nodes: each node is visited once, and the answer plus the widest level are stored.
class Solution:
def levelOrderBottom(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
if root is None:
return levels
current = [root]
while current:
level = []
next_level = [] # the nodes of the level below
for node in current:
level.append(node.val)
if node.left is not None:
next_level.append(node.left)
if node.right is not None:
next_level.append(node.right)
levels.append(level)
current = next_level
levels.reverse() # collected top-down, the answer is bottom-up
return levels
Now write it from memory
Close the write-up and solve it yourself against the tests.