FastPrepFind Leaves of a Binary Tree
Problem · Tree

Find Leaves of a Binary Tree

Learn this problem
MediumLinkedIn logoLinkedInFULLTIMEONSITE INTERVIEW

Problem 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 1 and 10000 nodes.
  • -10^9 <= Node.val <= 10^9.

More LinkedIn problems

drafts saved locally
public int[][] findLeaves(TreeNode root) {
    // Write your solution here.
}
root[1,2,3,4,5]
expected[[4,5,3],[2],[1]]
checking account