Find Leaves of Binary Tree
Given the root of a binary tree, collect its nodes as if you were repeatedly removing leaves:
- Collect all the current leaves and remove them from the tree.
- Repeat until the tree is empty.
Return the values removed in each round, one list per round. Within a round, list the leaves from left to right.
Trees in the examples and tests are written in level order, with null for a missing child.
Example 1
Input: root = [1, 2, 3, 4, 5] Output: [[4, 5, 3], [2], [1]] 1 / \ 2 3 / \ 4 5
The first round removes 4, 5 and 3. Then 2 is a leaf, and finally 1.
Example 2
Input: root = [1] Output: [[1]]
Constraints
- The tree has between
0and100nodes. -100 <= Node.val <= 100
Approach
Simulating the rounds means searching the whole tree once per round, which takes O(n²) time for a tree shaped like a chain. Look at when each node is removed instead. Leaves go in round 0. A parent becomes a leaf only after both of its children are gone, so it goes one round after its later child. That round is exactly the node's height: the number of edges on the longest path down to a leaf.
Compute heights with a post-order search, where each node's height is one more than the larger of its children's heights and an empty child counts as -1. As each node's height is known, append its value to the list for that height. The search visits the left subtree before the right one, so each round's list comes out left to right.
Steps
- Create an empty list of rounds.
- Define
height(node): return-1for an empty node. Otherwise, take one more than the larger height of the two children. - If that height is a new round, add an empty list, then append the node's value to the list for its height.
- Call
heighton the root and return the rounds.
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def find_leaves(root: Optional[TreeNode]) -> List[List[int]]:
rounds = []
def height(node: Optional[TreeNode]) -> int:
# a node is removed in the round equal to its height: leaves have height 0
if node is None:
return -1
h = 1 + max(height(node.left), height(node.right))
if h == len(rounds):
rounds.append([])
rounds[h].append(node.val)
return h
height(root)
return roundsComplexity
- Time:
O(n). Each node is visited once. - Space:
O(h)for the recursion, wherehis the height of the tree, plus the output.
Common mistakes
- Using depth from the root instead of height. Leaves can sit at different depths but are all removed in round 0.
- Counting an empty child as height 0, which makes every leaf height 1.
- In C++, writing
max(height(left), height(right))in one expression. C++ doesn't promise to evaluate the left call first, so a round can come out right to left. Compute the two heights on separate lines.