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:

  1. Identify all leaf nodes (nodes with no children)
  2. Collect them into a group
  3. Remove them from the tree
  4. 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
45321Layer 0: [4,5,3]Layer 1: [2]Layer 2: [1]Tree Nodes Grouped by Distance from Leaves
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

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h, plus O(n) for result storage

n
2n
โœ“ 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
Asked in
LinkedIn 35 Google 28 Amazon 22 Microsoft 18
52.0K Views
Medium Frequency
~15 min Avg. Time
1.8K 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