Construct Binary Tree from Parent Array
Submissions: 7850   Accuracy:

37.4%

  Difficulty: Medium   Marks: 4

Given an array of size N that represents a Tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation of Binary Tree from this array representation.

Input:
The first line of the input contains an integer 'T' denoting the number of test cases. Then 'T' test cases follow. Each test case consists of two lines. First line of each test case contains an integer N denoting the size of the tree array . Second line of each test case consists of 'N' space separated integers denoting the elements of the array .

Output:
The Output will be the sorted level order traversal of the tree.

User Task:
The task is complete the function 

Constraints:
1 <= T <= 100
1 <= N <= 103

Example:
Input:
2
7
-1 0 0 1 1 3 5
5
-1 0 0 2 2   

Output:
0 1 2 3 4 5 6
0 1 2 3 4

Explanation:
Testcase 1: For the array parent[] = {-1, 0, 0, 1, 1, 3, 5}; the tree generated will have a sturcture like

         0
       /   \
      1     2
     / \
    3   4
   /
  5
/
6

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Amit Khandelwal
Author: Shubham Joshi 1


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.