Find Leaves of Binary Tree - Problem
Find Leaves of Binary Tree challenges you to simulate a unique tree traversal pattern that peels away layers of a binary tree from the outside in.
Given the root of a binary tree, you need to collect nodes in a very specific way:
- Identify all leaf nodes (nodes with no children)
- Collect them into a group
- Remove them from the tree
- Repeat until the tree is completely empty
The goal is to return a List<List<Integer>> where each inner list contains the values of nodes removed in each iteration. This creates a beautiful onion-like peeling effect where we progressively remove outer layers until only the core remains.
Example: For a tree [1,2,3,4,5], we first remove leaves [4,5,3], then [2], and finally [1].
Input & Output
example_1.py โ Basic Binary Tree
$
Input:
root = [1,2,3,4,5]
โบ
Output:
[[4,5,3],[2],[1]]
๐ก Note:
First removal: leaves 4,5,3 (nodes with no children). Second removal: leaf 2 (after 4,5 removed). Third removal: leaf 1 (the root, now alone).
example_2.py โ Single Node
$
Input:
root = [1]
โบ
Output:
[[1]]
๐ก Note:
Tree has only one node which is both root and leaf, so it gets removed in the first iteration.
example_3.py โ Linear Tree
$
Input:
root = [1,2,null,3,null,4]
โบ
Output:
[[4],[3],[2],[1]]
๐ก Note:
This creates a left-skewed tree. Each level has only one node, so removal happens one node at a time from bottom to top.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Heights
Calculate each node's height: distance from being a leaf node
2
Group by Height
Nodes with same height belong to the same removal layer
3
Collect Results
Height 0 = first removal, height 1 = second removal, etc.
Key Takeaway
๐ฏ Key Insight: Instead of actually removing nodes multiple times, calculate each node's 'height' from leaves once and group them accordingly - this transforms an O(nยฒ) problem into O(n)!
Time & Space Complexity
Time Complexity
O(n)
Single DFS traversal visits each node exactly once
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h, plus O(n) for result storage
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [1, 100]
- Each node has a unique value
- Node values are in the range [-100, 100]
- The tree is a valid binary tree
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code