Problem · Tree
Find Leaves of a Binary Tree
Learn this problemProblem statement
You are given the root of a binary tree. Imagine removing every current leaf at the same time, recording their values, and repeating until the tree is empty.
Return one array per removal round. Within each round, values must appear in the same left-to-right order produced by a postorder traversal of the original tree.
A node belongs to round 0 when it is an original leaf. Otherwise, its round is one more than the larger round of its children.
Function
findLeaves(root: TreeNode) → int[][]Examples
Example 1
root = [1,2,3,4,5]return = [[4,5,3],[2],[1]]Nodes 4, 5, and 3 are removed first. Node 2 then becomes a leaf, followed by the root.
Example 2
root = [1,null,2,null,3]return = [[3],[2],[1]]The right-skewed chain exposes one leaf per round.
Constraints
- The tree contains between
1and10000nodes. -10^9 <= Node.val <= 10^9.