Print Tree LevelsEasy

Print Tree Levels

EasyPractice library · +10 XPtreestraversalsbfs

You are given a tree structure represented by a parent array. The parent array P of size N indicates that for each i from 1 to N-1, P[i] is the parent of node i. Node 0 is the root of the tree. Your task is to print the nodes level by level, starting from the root (level 0). For each level, print the nodes in increasing order. Within each level, print nodes separated by spaces. Each level should be printed on a new line.

Example: If N=5 and P=[ -1, 0, 0, 1, 1 ], node 0 is root. Its children are 1 and 2. Node 1's children are 3 and 4. Level 0: 0 Level 1: 1 2 Level 2: 3 4

Input

The first line contains an integer N, the number of nodes in the tree. The second line contains N integers P_0, P_1, ..., P_{N-1}, where P_i is the parent of node i. P_0 is always -1, indicating node 0 is the root.

Output

Print the nodes level by level. Nodes at each level should be printed in increasing order, separated by spaces. Each level should be on a new line.

Constraints

1 <= N <= 1000 -1 <= P_i < i for i > 0 P_0 == -1

Time limit 1 s (native code; slower languages get more)Memory 256 MB13 hidden tests

Example 1

Input
5
-1 0 0 1 1
Output
0
1 2
3 4

N=5, Parent array represents root 0, children 1 and 2. Node 1 has children 3 and 4.

Example 2

Input
7
-1 0 0 1 1 2 2
Output
0
1 2
3 4 5 6

N=7, a balanced tree of height 2.

Hints