15% off all plans & roadmaps Use code

See plans

Find Leaves of Binary Tree

Updated

TL;DR: A node is removed in the round equal to its height, so one postorder pass can sort every node into its round. The brute force peels the tree one round at a time and rescans the same nodes.

Problem

You are given the root of a binary tree. Remove all leaf nodes (nodes with no children) in rounds. In each round, collect the values of the leaves you remove, and keep going until the tree is empty.

Return a list of lists. Each inner list holds the values removed in one round, and the lists appear in the order the rounds happened.

Example 1

Input: root = [1]
Output: [[1]]

Constraints

  • The number of nodes in the tree is in the range [1, 100].
  • Each node's value is a unique integer.

Constraints that matter

  • The tree can have up to 100 nodes, so an O(N^2) solution fits the limit. The optimal pass still matters because it is the answer an interviewer expects you to reach.
  • The depth is at most 100, so a recursive walk is safe in every language on this page.
  • Values are unique, but the optimal solution never looks values up. It groups nodes by height, so duplicate values would not change the code.
  • The tree always has at least one node, so the root is never null at the start. The output is never empty.

View on LeetCode

Hints

Hint 1

The round a node leaves the tree depends on its children.

Hint 2

Do exactly what the statement says.

Solution

Intuition

The round a node leaves the tree depends on its children. A node with children cannot be a leaf, so it must wait until every child is gone. That dependency points to tree height and recursive postorder traversal, where you handle both children before the node itself.

Picture a stack of books where each book's level is one more than the tallest stack beneath it. The result list is the set of shelves, and each node is placed on the shelf matching the height returned to it.

The round number equals the node's height. A leaf has height 0. Any other node has height 1 plus the larger height of its two children. If the tallest child has height h, the node cannot leave before round h, and it leaves in round h + 1 once that child is gone.

Use -1 for a missing child. A leaf then computes 1 + max(-1, -1) = 0 and lands in round 0.

Take a tree where root 1 has left child 2 and right child 3, and node 2 has children 4 and 5. Nodes 4, 5 and 3 have height 0, node 2 has height 1, and the root has height 2. The rounds are [[4,5,3],[2],[1]].

This tree is only an illustration. The worked example on this page is the single-node tree.

Watch the pattern animation

Worked example

Input: root = [1], a tree with one node whose value is 1
Output: [[1]]
Explanation: The root has no children, so it is a leaf. Round 1 removes it and the tree becomes empty. The result has one list, and that list holds the value 1.

Approach 1: Brute force: peel leaves round by round

Do exactly what the statement says. Walk the whole tree, collect every leaf, detach those leaves, and repeat until the root is gone. Each walk visits every node that is still in the tree, so the top of the tree gets visited again and again.

This is the literal solution, and it is usually the first one people write. It is correct, and it is a good baseline to explain before you improve it.

Steps

  1. Create an empty list result.
  2. While the root is not null, create an empty list leaves for this round.
  3. Walk the tree. If a node has no children, append its value to leaves and return null to its parent.
  4. Otherwise, recurse into both children, store what each one returns, and return the node itself.
  5. Append leaves to result, then set the root to the value the walk returned.
  6. When the root is null, return result.

Dry run

On the example, root = [1], round 1 starts with the root. It has no children, so leaves becomes [1] and the walk returns null. The root is now null, so the loop stops. The result is [[1]], which matches the expected output.

Complexity

TimeO(N^2)
SpaceO(N)

Let N be the number of nodes. Each round walks every node that is still in the tree, and a tree of height H needs H + 1 rounds, which is at most N. On a skewed tree, round k walks N - k + 1 nodes, and those counts add up to about N^2 / 2. The output stores N values, and the recursion uses O(H) stack, which is at most O(N).

PythonTested in our runner

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        result = []
        while root is not None:
            leaves = []
            root = self._remove(root, leaves)
            result.append(leaves)
        return result

    def _remove(self, node, leaves):
        # Collect leaves and detach them, returning the new subtree root
        if node is None:
            return None
        if node.left is None and node.right is None:
            leaves.append(node.val)
            return None
        node.left = self._remove(node.left, leaves)
        node.right = self._remove(node.right, leaves)
        return node

The Recursive Postorder Traversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Recursive Postorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 2: One postorder pass with heightsOptimalRecursive Postorder Traversal

What is slow: the brute force walks the same upper nodes in every round. Nodes that have not changed still get visited again, so most of the work repeats.

The insight that fixes it: a node's round is its height, and you can compute every height in a single postorder walk. Each node goes straight into the list for its height, so no node is ever visited twice.

Steps

  1. Create an empty list result.
  2. Write a helper that returns the height of a node. Return -1 when the node is null.
  3. In the helper, get the left child's height and the right child's height first.
  4. Set the node's height to 1 plus the larger of the two child heights.
  5. If result has exactly that many lists, append a new empty list.
  6. Append the node's value to result[height] and return the height.
  7. Call the helper on the root and return result.

Dry run

Trace on root = [1]. The table has one row per step. The state columns are the two child heights, the node height, and the result.

StepActionLeft heightRight heightNode heightresult after step
1Enter node 1not known yetnot known yetnot known yet[]
2Enter left child, which is nulln/an/a-1[]
3Enter right child, which is nulln/an/a-1[]
4Back at node 1, compute height-1-11 + max(-1, -1) = 0[]
5Height 0 equals len(result) = 0, so append a list-1-10[[]]
6Add value 1 to result[0], return 0-1-10[[1]]

The final value is [[1]], which matches the expected output.

Complexity

TimeO(N)
SpaceO(N)

Let N be the number of nodes. The helper runs exactly once per node, and each call does constant work apart from its recursive calls, so time is O(N). Appending to a list takes amortized constant time. The output holds N values, and the call stack depth equals the tree height H, so space is O(N) including the output.

PythonTested in our runner

class Solution:
    def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
        result = []

        def height(node):
            # A missing child has height -1, so a leaf gets height 0
            if node is None:
                return -1
            left_h = height(node.left)
            right_h = height(node.right)
            h = 1 + max(left_h, right_h)
            # A new height is always exactly len(result), so append one list
            if h == len(result):
                result.append([])
            result[h].append(node.val)
            return h

        height(root)
        return result

Common mistakes

  • Returning 0 for a null child in the height helper. A leaf then computes 1 + max(0, 0) and lands in round 1 instead of round 0. Return -1 for null so every leaf gets height 0.
  • Writing result[h].append(node.val) without first checking h == len(result). When h is a new height, its list does not exist yet, so the index fails. Append an empty list first, then add the value.
  • Placing the height check above the recursive calls. The node's height is unknown until both children return. Compute both child heights first, then compare against len(result).
  • Writing max(height(node->left, result), height(node->right, result)) in C++. The order of those two calls is unspecified, so values can land in a different order inside a round. Store each child height in its own variable first.
  • In the brute force, using while root.left or root.right as the loop condition. A root that is itself a leaf fails that test, so its value is never recorded. Use while root instead.
  • Forgetting to assign the recursive results back to node.left and node.right in the brute force. Leaves stay attached, so the same nodes are collected every round. Return null from the leaf case and assign both children.

Edge cases

  • A single node, such as root = [1]. The output is [[1]].
  • A left-leaning chain 1 to 2 to 3, where each node has only a left child. Node 3 is round 0, node 2 is round 1, and node 1 is round 2. The output is [[3],[2],[1]].
  • A node with only one child, such as 1 with left child 2. Node 2 is round 0 and node 1 is round 1, so the output is [[2],[1]].
  • A perfect tree with 7 nodes. The rounds hold 4, 2 and 1 values, which gives sizes 4, 2 and 1 in order.
  • Negative values. The code never compares or hashes values, so negative numbers are copied into the right round without any change.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Find Leaves of Binary Tree, with how to answer them.

Unlock the follow-ups

Find Leaves of Binary Tree FAQ

What is the time complexity of Find Leaves of Binary Tree?

The optimal postorder solution runs in O(N) time, where N is the number of nodes, because it visits each node once. The brute force that peels leaves round by round runs in O(N^2) in the worst case, since it rescans the remaining tree each round.

Why use postorder traversal for Find Leaves of Binary Tree?

A node's round depends on its children, so the children must be handled first. Postorder visits the left subtree, then the right subtree, then the node itself. That is exactly the order the height calculation needs.

Can Find Leaves of Binary Tree be solved in O(1) extra space?

Not in the usual form. The recursive solution uses O(H) stack, and storing heights needs extra space unless you write them into the nodes. Output space is always O(N), so O(1) extra space needs advanced traversal tricks.

Why does Find Leaves of Binary Tree use -1 for null nodes?

The height of a leaf must be 0, and a leaf's children are null. With -1 for null, a leaf computes 1 + max(-1, -1) = 0. With 0 for null, the same leaf would compute 1 and land in the wrong list.

Does the order of values inside each round matter?

The statement fixes the order of the rounds, and the code emits each round from left to right. The order inside a round follows the tree's left-to-right layout, so the output is deterministic.

Asked at

See which companies ask this — Pro

Practise it