Peel an N-ary tree one leaf layer per day
Every day, all leaves of an N-ary tree fall off at the same time. A leaf is a node with no children left. When a node loses its last child, it becomes a leaf and falls on the next day, not the same day. This repeats until the tree is gone. The root always falls last.
Implement:
class Node:
val: int
children: list["Node"]
def leaves_by_day(root: Node | None) -> list[list[int]]: ...
Return days, where days[i] lists the values of the nodes removed on day i + 1. Values inside one day may be in any order. Return [] for an empty tree.
Constraints
-
0 <= n <= 10^5nodes. The tree can be very deep (a single chain). - Values are integers and may repeat. Treat every node as distinct.
- You do not need to change the tree. Just report the removal schedule.
Example 1
10
/ | \
20 30 40
/ \ |
50 60 70
Output: [[30, 50, 60, 70], [20, 40], [10]]. On day 1, 30, 50, 60 and 70 are leaves. On day 2, 20 and 40 have no children left. On day 3, only 10 is left.
Example 2
A chain 1 -> 2 -> 3 (each node has one child). Output: [[3], [2], [1]].
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
