Problem
Given a binary tree, collect a tree’s nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.
Examples
Example 1 Given binary tree
| |
Solution
The task is to simulate a process where we repeatedly collect all leaves of the binary tree and remove them, until the tree becomes empty. A “leaf” is a node that does not have any child nodes.
Method 1 - DFS with Returning Node Depth From Bottom
The solution lies in reformulating the problem as identifying the index of the element within the result list, which reduces it to a standard DFS problem on trees.
Approach
- Depth Calculation: Determine the depth at which a node turns into a leaf. A node becomes a leaf when all its children have been removed. By calculating the depth of each node’s removal, we can efficiently group nodes.
- Recursive Structure:
Use recursion to calculate the depth of nodes, where the depth is defined as
max(left, right) + 1. The leaves of the current depth can then be appended to the result list. - Base Case:
An empty node (
nullin Java orNonein Python) contributes nothing, so return -1 or equivalent.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n), due to traversal of each node once. - 🧺 Space complexity:
O(n). Using recursion stack takesO(h), wherehis the tree height for and thenO(n)for result storage.