Find Leaves of Binary Tree

MediumTreesdfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given the root of a binary tree, repeatedly strip the tree: collect all of its current leaves, remove them, and continue until the tree is empty. Return a list of groups, where group i holds the values of the leaves removed in round i (the first round first). Within each group, list values in **left-to-right** order as they appear in the tree. An empty tree yields [].

Examples

Input: root = [1,2,3,4,5]
Output: [[4,5,3],[2],[1]]
Round one removes leaves 4, 5, 3. Node 2 then becomes a leaf, and finally the root.
Input: root = [1]
Output: [[1]]
The root is a leaf.

Constraints

  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More dfs problems