Problem Description
Given the root of a binary tree, repeatedly remove the leaves of the tree until the tree becomes empty. At each step, collect and return the values of the leaves that were removed.
Key Insights
- Use a postorder traversal (bottom-up approach) to process the tree.
- Determine the "height" of each node (distance from the deepest leaf) where leaves have a height of 1.
- Group nodes by their computed height to simulate the layer-wise removal of leaves.
- The same node may become a leaf after its children are removed.
Space and Time Complexity
Time Complexity: O(n) — Each node is visited exactly once. Space Complexity: O(n) — Space used for the recursion stack and the result list.
Solution
The solution uses a recursive helper function that performs a postorder traversal of the tree. For each node, it computes its height as max(height of left, height of right) + 1. Nodes with the same height are collected together in a list. This idea mirrors the process of removing leaves level by level, where leaves (height 1) are removed first, then their parents become new leaves, and so on. Data Structures used:
- An array or list to maintain the groups of node values by their height. Algorithmic Approach:
- Use Depth-First Search (DFS) via recursion.
- Postorder traversal ensures that leaf nodes (base cases) are processed before their parents.
- Append the node's value to the correct list based on the computed height.