Find Leaves of Binary Tree Problem
Description
LeetCode Problem 366.
Given the root of a binary tree, collect a tree's nodes as if you were doing this:
- Collect all the leaf nodes.
- Remove all the leaf nodes.
- Repeat until the tree is empty.
Example 1:

Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Explanation:
[[3,5,4],[2],[1]] and [[3,4,5],[2],[1]] are also considered correct answers since per each level it does not matter the order on which elements are returned.
Example 2:
Input: root = [1]
Output: [[1]]
Constraints:
- The number of nodes in the tree is in the range
[1, 100]. -100 <= Node.val <= 100
Solution
Approach: Group Nodes by Height
We don't need to actually remove leaves round after round. In which round is a node removed? A leaf goes in round 0. A node becomes a leaf once both its children are gone, so it goes one round after the later of its two children. That is exactly the node's height: 0 for a leaf, and 1 + max(height(left), height(right)) otherwise, with an empty child counting as -1.
So a single post-order traversal answers the question. Compute each node's height from its children's heights, append the node's value to ans[height] (adding a new list when the height is reached for the first time), and return the height to the parent.
The children are always processed before their parent, and a parent's height is larger than its children's. So ans grows one level at a time, and the new list is always needed at index len(ans). Inside each round, the order of the values does not matter.
Complexity: O(n) time, each node is visited once. O(h) space for the recursion, where h is the height of the tree, plus the answer itself.
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
ans = []
# height of a node: 0 for a leaf, 1 + the taller child otherwise.
# A node is removed in round number height, so it goes into ans[height].
def height(node: Optional[TreeNode]) -> int:
if node is None:
return -1
h = max(height(node.left), height(node.right)) + 1
if h == len(ans):
ans.append([])
ans[h].append(node.val)
return h
height(root)
return ans