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   5
Inputroot = [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
Inputroot = [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

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate