Skip to main content

Find Leaves of Binary Tree

MediumPremium

Given the root of a binary tree, collect its nodes as if you were repeatedly removing leaves:

  1. Collect all the current leaves and remove them from the tree.
  2. Repeat until the tree is empty.

Return the values removed in each round, one list per round. Within a round, list the leaves from left to right.

Trees in the examples and tests are written in level order, with null for a missing child.

Example 1

Input: root = [1, 2, 3, 4, 5] Output: [[4, 5, 3], [2], [1]] 1 / \ 2 3 / \ 4 5

The first round removes 4, 5 and 3. Then 2 is a leaf, and finally 1.

Example 2

Input: root = [1] Output: [[1]]

Constraints

  • The tree has between 0 and 100 nodes.
  • -100 <= Node.val <= 100