A game's ability tree is rooted at a single starting ability, and every other ability is unlocked directly beneath exactly one prerequisite ability (an ability may have any number of abilities unlocked beneath it). Players unlock the tree tier by tier: tier 0 is the root alone, tier 1 holds everything unlocked directly beneath the root, tier 2 holds everything unlocked directly beneath a tier-1 ability, and so on. Given the full prerequisite structure, report the ability ids that belong to each tier.
Line 1: an integer N — the number of abilities. Abilities are numbered 1..N, and ability 1 is always the root. Next N-1 lines: two integers u v — ability v is unlocked directly beneath ability u (u is v's immediate prerequisite). The edges may appear in any order, and every ability other than the root appears as v in exactly one edge.
Print one line per tier, starting with tier 0 (the root) and continuing down to the deepest tier that contains at least one ability. Each line lists the ids belonging to that tier, in strictly increasing numeric order, separated by single spaces.
1 <= N <= 10^5 1 <= u, v <= N, u != v The edges, together with root 1, form a valid rooted tree.
Example 1
Input
7 1 2 1 3 1 4 2 5 2 6 4 7
Expected
1 2 3 4 5 6 7
Explanation
The root ability 1 directly unlocks abilities 2, 3 and 4, so tier 1 is "2 3 4". Ability 2 unlocks 5 and 6, and ability 4 unlocks 7, so tier 2 is "5 6 7". The output is three lines: "1", "2 3 4", "5 6 7".
Example 2
Input
1
Expected
1
Explanation
There are no edges at all, so the only ability is the root itself. The output is a single line containing just "1" (tier 0).
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →