Mid/Senior
Find Leaves of Binary Tree
Given the root of a binary tree, collect the tree's nodes as if you were repeatedly removing all current leaf nodes.
In each round:
- Find all current leaves of the tree.
- Add their values to the current round's list, from left to right.
- Remove those leaves from the tree.
Return a list of lists where the ith list contains the values of the leaves removed in the ith round, continuing until the tree is empty.
Example 1
1
/ \
2 3
/ \
4 5Input
root = [1,2,3,4,5]Output
[[4,5,3],[2],[1]]The first round removes leaves 4, 5, and 3; the second removes 2; the final round removes 1.
Example 2
1
Input
root = [1]Output
[[1]]The only node is also a leaf, so it is removed in the first round.
Constraints
- The number of nodes in the tree is in the range [1, 100]
- -100 <= Node.val <= 100