Construct Binary Tree from Parent Array | Practice | GeeksforGeeks

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.
Note: If two elements have the same parent, the one that appears first in the array will be the left child and the other is the right child. 

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
0
triloki352 weeks ago
 /***** C++ **********/      Node* root = NULL;   Node *createTree(int parent[], int N)   {             unordered_map<int,Node*> mp;              // all the nodes of tree are indexs of parent[]        // so making all possible nodes and filling it in map       for(int i=0;i<N;i++)       {           Node* temp = new Node(i);           mp[i]=temp;       }              // connecting all nodes       for(int i=0;i<N;i++)       {           // root condition           if(parent[i]==-1)           {              auto it = mp.find(i);               root = it->second;           }           else           {               // searching for parent of "i" in map               auto parent_it = mp.find(parent[i]);               Node* parent = parent_it->second;                              // finding address of node wiht value i in map               auto child_it = mp.find(i);               Node* child = child_it->second;                              if(parent->left==NULL)                   parent->left = child;               else                   parent->right = child;           }         }              return root;   }
0
aryanm4682 weeks ago
class Solution{ public:   //Function to construct binary tree from parent array.   Node *createTree(int parent[], int N)   {       // Your code here              Node *head=NULL;       unordered_map<int,Node*> u;              for(int i=0; i<N; i++)       {           Node* curr;                      if(u.find(i)==u.end())               curr= new Node(i);           else              {                  auto it =u.find(i);                  curr=it->second;              }               if(parent[i]==-1)           {               head=curr;           }         else         {           if(u.find(parent[i])==u.end())           {                Node *dummy= new Node(parent[i]);                dummy->left=curr;                                u[parent[i]]=dummy;           }           else           {               auto it =u.find(parent[i]);               Node *dummy=it->second;                              if(dummy->left==NULL)                dummy->left=curr;                              else               dummy->right=curr;           }          }          u[i]=curr;       }       return head;   }};
0
amankumar2783 weeks ago
Java Solution:
using ArrayList<Node>
 
class Solution{   //Function to construct binary tree from parent array.   public static Node createTree(int arr[], int n)   {       //Your code here       if(n==0){           Node temp=null;           return temp;       }       ArrayList<Node> list= new ArrayList<>();       for(int i=0;i<n;i++){           Node temp=new Node(i);           list.add(temp);       }       Node root=null;       for(int i=0;i<n;i++){           if(arr[i]==-1){               root=list.get(i);               continue;           }          Node temp=list.get(arr[i]);          if(temp.left==null){              temp.left=list.get(i);          }else{              temp.right=list.get(i);          }       }       return root;   }  }
 
0
abrajput15063 weeks ago
vector<int> search(int a[],int n,int data){
        vector<int> v(2,-1);
        int t = 0;
        for(int i=0;i<n;i++)
            if(a[i] == data)
                v[t++] = i;
        return v;
    }
    Node* helper(int p[],int n,int idx){
        if(idx == -1)
            return NULL;
        
        Node* node = new Node(idx);
        vector<int> v = search(p,n,idx);
        
        node->left = helper(p,n,v[0]);
        node->right = helper(p,n,v[1]);
        
        return node;
    }
    Node *createTree(int parent[], int N)
    {
        // Your code here
        Node* root = NULL;
        int idx = -1;
        for(int i=0;i<N;i++)
            if(parent[i] == -1)
                idx = i;
        root = helper(parent,N,idx);
        return root;
    }
0
gujjulassr1 month ago
3.7/5.5
 
class Solution{   //Function to construct binary tree from parent array.   public static Node createTree(int arr[], int N)   {       //Your code here       Node[] a=new Node[N];       Node head=null;       for(int i=0;i<arr.length;i++){           if(arr[i]!=-1){               a[i]=new Node(i);           }else{               head=new Node(i);               a[i]=head;           }       }       for(int i=0;i<N;i++){           if(arr[i]!=-1){               if(a[arr[i]].left==null){                   a[arr[i]].left=a[i];               }               else if(a[arr[i]].right==null){                   a[arr[i]].right=a[i];               }           }       }       return head;   }   }
0
aniketkumar51 month ago
 public static Node root4;   public static Node createTree(int parent[], int N)   {       //Your code here             Node[] created = new Node[N];              for(int i=0;i<N;i++){           created[i]=null;       }       for(int i=0;i<N;i++){          createNode(parent, i, created);       }       return root4;   }   public static void createNode(int parent[],int i, Node[] root){              if(root[i]!=null){          return ;      }      root[i]=new Node(i);      if(parent[i]==-1){          root4=root[i];         return ;      }      if(root[parent[i]]==null){              createNode(parent,parent[i],root);          }          Node p=root[parent[i]];      if(p.left==null){             p.left = root[i];          }          else{               p.right = root[i];          }             }
0
salwayhrishikesh2 months ago
public static void createParent(int parent, int value, Node [] nodes){
        // adding the current node in the visited list
        if(nodes[value] == null)
            nodes[value] = new Node(value);
        
        // if current node is the root node then exit out of the function
        if (parent == -1)
            return;
        
        // creating a node for parent
        Node temp = null;
        
        // checking if the parent node has been visited before
        temp = nodes[parent] == null ? new Node(parent) : nodes[parent];
        nodes[parent] = temp;
        
        // if the parent node has no left child
        if (temp.left == null){
            temp.left = nodes[value];
        }
        
        // if the parent node has no right child
        else{
            temp.right = nodes[value];
        }
        
    }
    
    //Function to construct binary tree from parent array.
    
    public static Node createTree(int parent[], int N)
    {
        int root = 0;
        Node [] nodes = new Node[N];
        
        for (int i = 0; i < N; i ++){
            createParent(parent[i], i, nodes);
            if (parent[i] == -1)
                root = i;
        }
        
        return nodes[root];
    }
0
sankt2 months ago
Simple JAVA solution:    
    
    public static Node createTree(int parent[], int N)
    {
        Node root = null;
        
        HashMap<Integer, Node> hm = new HashMap<>();
        
        for (int i=0; i<N; i++) {
            if (parent[i] == -1) {
                root = new Node(i);
                hm.put(i, root);
            } else {
                Node temp = new Node(i);
                hm.put(i, temp);   
            }
        }
        
        for (int i=0; i<N; i++) {
            if (parent[i] == -1) continue;
            Node temp = hm.get(parent[i]);
            
            if (temp.left == null) {
                temp.left = hm.get(i);
            } else {
                temp.right = hm.get(i); 
            }
        }
        
        return root;
    }
0
priyanshugupta1231232 months ago
Perfect JAVA Solution :
class Solution
{
    //Function to construct binary tree from parent array.
    public static Node createTree(int parent[], int N)
    {
        if(N==0)
            return null;
            
        Map<Integer,PairClass> map = new HashMap<>();
        Node root = new Node(1);
        int i = 0 ;
        for(int n : parent){
            if(n==-1){
                root = new Node(i);
                i++;
                continue;
            }
            PairClass pair = map.get(n);
            if(pair==null){
                pair = new PairClass(i);
            }else{
                pair.set2(i);
            }
            map.put(n,pair);
            i++;
        }
 
        Queue<Node> q = new ArrayDeque<>();
        q.add(root);
        
        while(!q.isEmpty()){
            Node n = q.remove();
            PairClass p;
            if(map.get(n.data)!=null)
                p = map.get(n.data);
            else
                continue;
            if(p.isFilled){
                Node left = new Node(p.val1);
                Node right = new Node(p.val2);
                n.left = left;
                n.right = right;
                q.add(left);
                q.add(right);
            }else{
                Node left = new Node(p.val1);
                n.left = left;
                q.add(left);
            }            
        }
        return root;
        
    }
    public static void p(int i){
        System.out.println(String.valueOf(i));
    }
    
    public static void p(String i){
        System.out.println(i);
    }
}

class PairClass{
    int val1, val2;
    boolean isFilled = false;
    PairClass(int val){
        this.val1 = val;
    }
    public void set2(int val){
        isFilled = true;
        this.val2 = val;
    }
    public void printEle(){
        if(isFilled)
            System.out.println(String.valueOf(val1) + " " + String.valueOf(val2));
        else
            System.out.println(String.valueOf(val1));
    } 
}

0
tharunreddy09212 months ago
java solution
class Solution{   //Function to construct binary tree from parent array.   public static Node createTree(int parent[], int N)   {       //Your code here       int rn=0;       ArrayList<Node> al=new ArrayList<>();       //to find the root element;       for(int i=0;i<parent.length;i++)       {           if(parent[i]==-1)           {               rn=i;               break;           }       }              for(int i=0;i<parent.length;i++)       {           Node x=new Node(i);           al.add(x);       }              for(int i=0;i<parent.length;i++)       {           if (i==rn)           continue;           Node x=al.get(parent[i]);           if(x.left==null)           x.left=al.get(i);           else           x.right=al.get(i);       }       return al.get(rn);          }   }
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.