Leaderboard
Showing:
Handle Score
@Ibrahim Nash 6420
@blackshadows 6380
@mb1973 5642
@Quandray 5233
@akhayrutdinov 5111
@saiujwal13083 4610
@sanjay05 3762
@kirtidee18 3673
@marius_valentin_dragoi 3522
@sushant_a 3459
@verma_ji 3413
Complete Leaderboard
Construct Binary Tree from Parent Array
Medium Accuracy: 45.96% Submissions: 20160 Points: 4

Given an array of size N that can be used to represents a tree. The 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.

 

Example 1:

Input:
N = 7
parent[] = {-1,0,0,1,1,3,5}
Output: 0 1 2 3 4 5 6
Explanation: the tree generated
will have a structure like 
          0
        /   \
       1     2
      / \
     3   4
    /
   5
 /
6

 

Example 2:

Input:
N = 3
parent[] = {2, 0, -1}
Output: 2 0 1
Explanation: the tree generated will
have a sturcture like
               2
             /   
            0      
          /   
         1     

 

Your Task:
You don't need to read input or print anything. The task is to complete the function createTree() which takes 2 arguments parent[] and N and returns the root node of the constructed tree.

 

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)

 

Constraints:
1 <= N <= 103

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Construct Binary Tree from Parent Array

Output Window