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
Find Leaves of Binary Tree - Layer by LayerOriginal Tree12345After Step 112After Step 21Step 1: [4,5,3]Step 2: [2]Step 3: [1]Final Result: [[4,5,3],[2],[1]]
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
Asked in
Google 25 Amazon 18 Facebook 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen