Find Leaves of Binary Tree

Medium

Topics
TreeDFSBinary Tree

Given the root of a binary tree, collect its nodes as follows: take all the leaves and remove them, then take all the leaves of what is left and remove those, and so on until the tree is empty.

Return the collected groups in the order they were removed.

Within a group, list the values left to right as they stood in the tree, so the answer is unambiguous.

On this judge the groups are shown separated by |.

Example 1

4round 12round 25round 11round 33round 1
removed firstremoved secondremoved third or later
A round strips every node that currently has no children, and the label beside each node is the round that reaches it. Note that a node high in the tree can go in the first round — what matters is having nothing below it, not sitting near the leaves. The 3 rounds here peel off [[4,5,3],[2],[1]].
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation: The first round removes 4, 5 and 3. That leaves 1 with a single child 2, which is removed next, and finally the root.

Example 2

1round 1
removed first
Input:  root = [1]
Output: [[1]]
Explanation: The root is itself a leaf, so one round empties the tree.

Example 3

3round 12round 21round 3
removed firstremoved secondremoved third or later
Input:  root = [1,2,null,3]
Output: [[3],[2],[1]]
Explanation: A left-leaning chain peels one node per round.

Constraints

  • 1 <= number of nodes <= 100
  • -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls

Intuition

Repeatedly scanning for leaves and deleting them is the literal reading, and it rebuilds the same information over and over. The useful reframing is to ask, for each node, which round will remove it.

A node is removed once both its subtrees are gone. So its round is one more than the later of its children’s rounds — which is exactly the node’s height, the distance to its deepest descendant leaf. A leaf has height 0 and goes in round 0; its parent has height 1 and goes in round 1.

That turns the whole thing into a single traversal: compute each node’s height bottom-up and file its value under that height. No node is ever deleted and no round is ever re-scanned.

Approach

  1. Recurse to the bottom of the tree, returning each node’s height. An absent child contributes height -1 so a leaf comes out as 0.
  2. At each node, take one more than the larger of its two children’s heights.
  3. Append the node’s value to the group indexed by that height, creating the group the first time it is reached.
  4. Visit the left subtree before the right, which fills every group left to right as the statement requires. Return the groups in index order.

Walkthrough

root = [1,2,3,4,5]

        1
       / \
      2   3
     / \
    4   5

node   height   group
  4       0     0: [4]
  5       0     0: [4,5]
  2       1     1: [2]
  3       0     0: [4,5,3]
  1       2     2: [1]

answer [[4,5,3],[2],[1]]

Note 3 joins group 0 after 5 even though it sits higher
in the tree -- the group is by removal round, and within
it the order is left to right.

Complexity

  • Time — O(n): one visit per node, with constant work each. The repeated-deletion reading is O(n²) on a path-shaped tree.
  • Space — O(n): the recursion depth, which is the tree height, plus one stored value per node in the groups.

Common Pitfalls

  • Using depth from the root rather than height from the leaves. Those only agree on a perfectly balanced tree — in example 1 the node 3 has depth 1 but height 0, and it belongs with the leaves.
  • Visiting the right subtree first, which reverses the order within each group.
  • Returning 0 for an absent child instead of -1, which puts every leaf in group 1 and leaves group 0 empty.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def findLeaves(self, root):
        groups = []

        def height(node):
            if not node:
                return -1
            h = 1 + max(height(node.left), height(node.right))
            if h == len(groups):
                groups.append([])
            groups[h].append(node.val)
            return h

        height(root)
        return groups
SensAI
Beta
Tap the mic to stop voice mode