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 INPUT Binary Tree Structure: 1 2 3 4 5 = Leaf node = Internal root = [1,2,3,4,5] Array representation ALGORITHM STEPS 1 DFS Traversal Traverse tree bottom-up 2 Calculate Height Leaf = 0, else max(L,R)+1 3 Group by Height result[height] = node.val 4 Return Result 2D array of grouped nodes Height Calculation: Node Height Group 4, 5, 3 0 [0] 2 1 [1] 1 2 [2] h = max(left_h, right_h) + 1 FINAL RESULT Round 1: Remove leaves 1 2 [4, 5, 3] Round 2: Remove leaves 1 [2] Round 3: Remove root [1] Output: [[4,5,3],[2],[1]] Key Insight: The height of a node determines which round it gets removed. Leaves have height 0, their parents have height 1, and so on. Using DFS, we calculate heights bottom-up and group nodes by height. Time: O(n), Space: O(n) for recursion and result storage. TutorialsPoint - Find Leaves of Binary Tree | DFS Height-Based Grouping
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