Find Leaves of Binary Tree - Problem
Given the root of a binary tree, collect a tree's nodes as if you were doing this:
1. Collect all the leaf nodes, remove all the leaf nodes.
2. Repeat until the tree is empty.
Return a 2D array where each sub-array contains all the nodes removed at each step.
Definition: A leaf is a node with no left and right children.
Input & Output
Example 1 — Standard Tree
$
Input:
root = [1,2,3,4,5]
›
Output:
[[4,5,3],[2],[1]]
💡 Note:
Step 1: Remove leaves [4,5,3]. Step 2: Remove leaves [2]. Step 3: Remove leaves [1].
Example 2 — Single Node
$
Input:
root = [1]
›
Output:
[[1]]
💡 Note:
Only one node, which is a leaf, so remove it in the first step.
Example 3 — Linear Tree
$
Input:
root = [1,2,null,3,null,4]
›
Output:
[[4],[3],[2],[1]]
💡 Note:
Linear tree: each level has one leaf. Remove 4, then 3, then 2, then 1.
Constraints
- The number of nodes in the tree is in the range [1, 100]
- -100 ≤ Node.val ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with nodes [1,2,3,4,5]
2
Remove Leaves
Iteratively remove leaf nodes layer by layer
3
Group Results
Collect removed nodes at each step: [[4,5,3],[2],[1]]
Key Takeaway
🎯 Key Insight: A node's removal order equals its height from the bottom of the tree
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code