Given an array parent[] where each index represents a node and parent[i] gives the parent’s index, with -1 indicating the root. Your task is to construct the binary tree in standard linked-node form (each node having left and right pointers) based on this parent–child relationship and return the root node.
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.
Examples:
Input: parent[] = [-1, 0, 0, 1, 1, 3, 5] Output: [0, 1, 2, 3, 4, N, N, 5, N, N, N, 6] Explanation: The tree generated will have a structure like:
Input: parent[] = [2, 0, -1] Output: [2, 0, N, 1] Explanation: The tree generated will have a structure like:
[Naive Approach] Brute Force Approach - O(n^2) Time and O(n) Space
The idea is to first create all the tree nodes and then, for every node, search the parent[] array to find its parent node.
Once the parent is found, we attach the current node as the left child if the left pointer is empty; otherwise, we attach it as the right child.
Create one Node for every index and store them in an array.
Traverse every node i from 0 to n - 1.
If parent[i] == -1, mark node i as the root.
Otherwise, search for the node whose index is parent[i].
Attach node i to the parent's left child if it is empty; otherwise attach it to the right.
Return the root node.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};Node*createTree(vector<int>&parent){intn=parent.size();// Create all nodes.vector<Node*>nodes(n);for(inti=0;i<n;i++)nodes[i]=newNode(i);Node*root=nullptr;// Process every node.for(inti=0;i<n;i++){// If parent is -1, this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Search for the parent node.Node*p=nullptr;for(intj=0;j<n;j++){if(j==parent[i]){p=nodes[j];break;}}// Attach as the left child if empty.if(p->left==nullptr)p->left=nodes[i];// Otherwise, attach as the right child.elsep->right=nodes[i];}returnroot;}// Function to print level order traversal.voidlevelOrder(Node*root){if(root==nullptr)return;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();cout<<curr->data<<" ";if(curr->left!=nullptr)q.push(curr->left);if(curr->right!=nullptr)q.push(curr->right);}}intmain(){vector<int>parent={-1,0,0,1,1,3,5};Node*root=createTree(parent);levelOrder(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{staticNodecreateTree(int[]parent){intn=parent.length;Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Process every nodefor(inti=0;i<n;i++){// If this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Search for the parent node.Nodep=null;for(intj=0;j<n;j++){if(j==parent[i]){p=nodes[j];break;}}// Attach as the left child if empty.if(p.left==null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.staticvoidlevelOrder(Noderoot){if(root==null)return;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){Nodecurr=q.poll();System.out.print(curr.data+" ");if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}}publicstaticvoidmain(String[]args){int[]parent={-1,0,0,1,1,3,5};Noderoot=createTree(parent);levelOrder(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefcreateTree(parent):n=len(parent)# Create all nodes.nodes=[None]*nforiinrange(n):nodes[i]=Node(i)root=None# Process every node.foriinrange(n):# If this node is the root.ifparent[i]==-1:root=nodes[i]continue# Search for the parent node.p=Noneforjinrange(n):ifj==parent[i]:p=nodes[j]break# Attach as the left child if empty.ifp.leftisNone:p.left=nodes[i]# Otherwise, attach as the right child.else:p.right=nodes[i]returnroot# Function to print level order traversal.deflevelOrder(root):ifrootisNone:returnq=deque()q.append(root)whileq:curr=q.popleft()print(curr.data,end=" ")ifcurr.leftisnotNone:q.append(curr.left)ifcurr.rightisnotNone:q.append(curr.right)# Driver Codeif__name__=="__main__":parent=[-1,0,0,1,1,3,5]root=createTree(parent)levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{staticNodecreateTree(int[]parent){intn=parent.Length;// Create all nodes.Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Process every node.for(inti=0;i<n;i++){// If this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Search for the parent node.Nodep=null;for(intj=0;j<n;j++){if(j==parent[i]){p=nodes[j];break;}}// Attach as the left child if empty.if(p.left==null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.staticvoidlevelOrder(Noderoot){if(root==null)return;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();Console.Write(curr.data+" ");if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}}publicstaticvoidMain(){int[]parent={-1,0,0,1,1,3,5};Noderoot=createTree(parent);levelOrder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functioncreateTree(parent){constn=parent.length;// Create all nodes.constnodes=newArray(n);for(leti=0;i<n;i++)nodes[i]=newNode(i);letroot=null;// Process every node.for(leti=0;i<n;i++){// If this node is the root.if(parent[i]===-1){root=nodes[i];continue;}// Search for the parent node.letp=null;for(letj=0;j<n;j++){if(j===parent[i]){p=nodes[j];break;}}// Attach as the left child if empty.if(p.left===null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.functionlevelOrder(root){if(root===null)return;constq=[];letidx=0;q.push(root);letres="";while(idx<q.length){constcurr=q[idx++];res+=curr.data+" ";if(curr.left!==null)q.push(curr.left);if(curr.right!==null)q.push(curr.right);}console.log(res.trim());}// Driver Codeconstparent=[-1,0,0,1,1,3,5];constroot=createTree(parent);levelOrder(root);
Output
0 1 2 3 4 5 6
[Expected Approach] Create All Nodes First and Link Them - O(n) Time and O(n) Space
The idea is to first create one node for every index and store all node pointers in an array. Since the node index directly corresponds to its position in parent[], we can directly access any parent node using nodes[parent[i]].
Then, while traversing the parent array from left to right, attach each node to its parent's left child if it is empty; otherwise, attach it to the right. This also naturally preserves the required left-to-right child order.
Create an array nodes[] and create one node for every index.
Traverse parent[] from left to right.
If parent[i] == -1, make nodes[i] the root.
Otherwise, directly access the parent using nodes[parent[i]].
Attach the current node as the left child if it is empty; otherwise attach it as the right child.
Return the root node.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=right=nullptr;}};Node*createTree(vector<int>&parent){intn=parent.size();// Create all nodes.vector<Node*>nodes(n);for(inti=0;i<n;i++)nodes[i]=newNode(i);Node*root=nullptr;// Process every node.for(inti=0;i<n;i++){// If this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Get the parent node directly.Node*p=nodes[parent[i]];// Attach as the left child if empty.if(p->left==nullptr)p->left=nodes[i];// Otherwise, attach as the right child.elsep->right=nodes[i];}returnroot;}// Function to print level order traversal.voidlevelOrder(Node*root){if(root==nullptr)return;queue<Node*>q;q.push(root);while(!q.empty()){Node*curr=q.front();q.pop();cout<<curr->data<<" ";if(curr->left!=nullptr)q.push(curr->left);if(curr->right!=nullptr)q.push(curr->right);}}intmain(){vector<int>parent={-1,0,0,1,1,3,5};Node*root=createTree(parent);levelOrder(root);return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=right=null;}}classGFG{staticNodecreateTree(int[]parent){intn=parent.length;// Create all nodes.Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Process every node.for(inti=0;i<n;i++){// If this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Get the parent node directly.Nodep=nodes[parent[i]];// Attach as the left child if empty.if(p.left==null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.staticvoidlevelOrder(Noderoot){if(root==null)return;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){Nodecurr=q.poll();System.out.print(curr.data+" ");if(curr.left!=null)q.add(curr.left);if(curr.right!=null)q.add(curr.right);}}publicstaticvoidmain(String[]args){int[]parent={-1,0,0,1,1,3,5};Noderoot=createTree(parent);levelOrder(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefcreateTree(parent):n=len(parent)# Create all nodes.nodes=[None]*nforiinrange(n):nodes[i]=Node(i)root=None# Process every node.foriinrange(n):# If this node is the root.ifparent[i]==-1:root=nodes[i]continue# Get the parent node directly.p=nodes[parent[i]]# Attach as the left child if empty.ifp.leftisNone:p.left=nodes[i]# Otherwise, attach as the right child.else:p.right=nodes[i]returnroot# Function to print level order traversal.deflevelOrder(root):ifrootisNone:returnq=deque()q.append(root)whileq:curr=q.popleft()print(curr.data,end=" ")ifcurr.leftisnotNone:q.append(curr.left)ifcurr.rightisnotNone:q.append(curr.right)# Driver Codeif__name__=="__main__":parent=[-1,0,0,1,1,3,5]root=createTree(parent)levelOrder(root)
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=right=null;}}classGFG{staticNodecreateTree(int[]parent){intn=parent.Length;// Create all nodes.Node[]nodes=newNode[n];for(inti=0;i<n;i++)nodes[i]=newNode(i);Noderoot=null;// Process every node.for(inti=0;i<n;i++){// If this node is the root.if(parent[i]==-1){root=nodes[i];continue;}// Get the parent node directly.Nodep=nodes[parent[i]];// Attach as the left child if empty.if(p.left==null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.staticvoidlevelOrder(Noderoot){if(root==null)return;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){Nodecurr=q.Dequeue();Console.Write(curr.data+" ");if(curr.left!=null)q.Enqueue(curr.left);if(curr.right!=null)q.Enqueue(curr.right);}}publicstaticvoidMain(){int[]parent={-1,0,0,1,1,3,5};Noderoot=createTree(parent);levelOrder(root);}}
JavaScript
classNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functioncreateTree(parent){constn=parent.length;// Create all nodes.constnodes=newArray(n);for(leti=0;i<n;i++)nodes[i]=newNode(i);letroot=null;// Process every node.for(leti=0;i<n;i++){// If this node is the root.if(parent[i]===-1){root=nodes[i];continue;}// Get the parent node directly.constp=nodes[parent[i]];// Attach as the left child if empty.if(p.left===null)p.left=nodes[i];// Otherwise, attach as the right child.elsep.right=nodes[i];}returnroot;}// Function to print level order traversal.functionlevelOrder(root){if(root===null)return;constq=[];letidx=0;q.push(root);letres="";while(idx<q.length){constcurr=q[idx++];res+=curr.data+" ";if(curr.left!==null)q.push(curr.left);if(curr.right!==null)q.push(curr.right);}console.log(res.trim());}// Driver Codeconstparent=[-1,0,0,1,1,3,5];constroot=createTree(parent);levelOrder(root);