Construct Binary Tree from given Parent Array representation | Iterative Approach
Last Updated :
01 Feb, 2023
Given an array 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 given Binary Tree from this given representation.
Examples:
Input: parent[] = {1, 5, 5, 2, 2, -1, 3}
Output:
Inorder Traversal of constructed tree
0 1 5 6 3 2 4
5
/ \
1 2
/ / \
0 3 4
/
6
Index of -1 is 5. So 5 is root.
5 is present at indexes 1 and 2. So 1 and 2 are
children of 5.
1 is present at index 0, so 0 is child of 1.
2 is present at indexes 3 and 4. So 3 and 4 are
children of 2.
3 is present at index 6, so 6 is child of 3.
Input: parent[] = {-1, 0, 0, 1, 1, 3, 5}
Output:
Inorder Traversal of constructed tree
6 5 3 1 4 0 2
0
/ \
1 2
/ \
3 4
/
5
/
6
Approach: Recursive approach to this problem is discussed here.
Following is the iterative approach:
1. Create a map with key as the array index and its
value as the node for that index.
2. Start traversing the given parent array.
3. For all elements of the given array:
(a) Search the map for the current index.
(i) If the current index does not exist in the map:
.. Create a node for the current index
.. Map the newly created node with its key by m[i]=node
(ii) If the key exists in the map:
.. it means that the node is already created
.. Do nothing
(b) If the parent of the current index is -1, it implies it is
the root of the tree
.. Make root=m[i]
Else search for the parent in the map
(i) If the parent does not exist:
.. Create the parent node.
.. Assign the current node as its left child
.. Map the parent node(as in Step 3.(a).(i))
(ii) If the parent exists:
.. If the left child of the parent does not exist
-> Assign the node as its left child
.. Else (i.e. right child of the parent does not exist)
-> Assign the node as its right child
This approach works even when the nodes are not given in order.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
struct Node *left, *right;
};
Node* newNode( int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->key << " " ;
inorder(root->right);
}
}
Node* createTree( int parent[], int n)
{
map< int , Node*> m;
Node *root, *temp;
int i;
for (i = 0; i < n; i++) {
if (m.find(i) == m.end()) {
temp = newNode(i);
m[i] = temp;
}
if (parent[i] == -1)
root = m[i];
else if (m.find(parent[i]) == m.end()) {
temp = newNode(parent[i]);
temp->left = m[i];
m[parent[i]] = temp;
}
else {
if (!m[parent[i]]->left)
m[parent[i]]->left = m[i];
else
m[parent[i]]->right = m[i];
}
}
return root;
}
int main()
{
int parent[] = { -1, 0, 0, 1, 1, 3, 5 };
int n = sizeof parent / sizeof parent[0];
Node* root = createTree(parent, n);
cout << "Inorder Traversal of constructed tree\n" ;
inorder(root);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int key;
Node left, right;
};
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return (temp);
}
static void inorder(Node root)
{
if (root != null )
{
inorder(root.left);
System.out.print( root.key + " " );
inorder(root.right);
}
}
static Node createTree( int parent[], int n)
{
HashMap<Integer, Node> m= new HashMap<>();
Node root= new Node(), temp= new Node();
int i;
for (i = 0 ; i < n; i++)
{
if (m.get(i) == null )
{
temp = newNode(i);
m.put(i, temp);
}
if (parent[i] == - 1 )
root = m.get(i);
else if (m.get(parent[i]) == null )
{
temp = newNode(parent[i]);
temp.left = m.get(i);
m.put(parent[i],temp);
}
else
{
if (m.get(parent[i]).left == null )
m.get(parent[i]).left = m.get(i);
else
m.get(parent[i]).right = m.get(i);
}
}
return root;
}
public static void main(String args[])
{
int parent[] = { - 1 , 0 , 0 , 1 , 1 , 3 , 5 };
int n = parent.length;
Node root = createTree(parent, n);
System.out.print( "Inorder Traversal of constructed tree\n" );
inorder(root);
}
}
|
Python3
class Node:
def __init__( self ):
self .key = 0
self .left = None
self .right = None
def newNode(key: int ) - > Node:
temp = Node()
temp.key = key
temp.left = None
temp.right = None
return temp
def inorder(root: Node):
if root is not None :
inorder(root.left)
print (root.key, end = " " )
inorder(root.right)
def createTree(parent: list , n: int ) - > Node:
m = dict ()
root = Node()
for i in range (n):
if i not in m:
temp = newNode(i)
m[i] = temp
if parent[i] = = - 1 :
root = m[i]
elif parent[i] not in m:
temp = newNode(parent[i])
temp.left = m[i]
m[parent[i]] = temp
else :
if m[parent[i]].left is None :
m[parent[i]].left = m[i]
else :
m[parent[i]].right = m[i]
return root
if __name__ = = "__main__" :
parent = [ - 1 , 0 , 0 , 1 , 1 , 3 , 5 ]
n = len (parent)
root = createTree(parent, n)
print ( "Inorder Traversal of constructed tree" )
inorder(root)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
class Node
{
public int key;
public Node left, right;
};
static Node newNode( int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return (temp);
}
static void inorder(Node root)
{
if (root != null )
{
inorder(root.left);
Console.Write( root.key + " " );
inorder(root.right);
}
}
static Node createTree( int []parent, int n)
{
Dictionary< int , Node> m = new Dictionary< int , Node>();
Node root = new Node(), temp = new Node();
int i;
for (i = 0; i < n; i++)
{
if (!m.ContainsKey(i))
{
temp = newNode(i);
m.Add(i, temp);
}
if (parent[i] == -1)
root = m[i];
else if (!m.ContainsKey(parent[i]))
{
temp = newNode(parent[i]);
temp.left = m[i];
m.Add(parent[i], temp);
}
else
{
if (m[parent[i]].left == null )
m[parent[i]].left = m[i];
else
m[parent[i]].right = m[i];
}
}
return root;
}
public static void Main(String []args)
{
int []parent = { -1, 0, 0, 1, 1, 3, 5 };
int n = parent.Length;
Node root = createTree(parent, n);
Console.Write( "Inorder Traversal of constructed tree\n" );
inorder(root);
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .key = val;
this .left = null ;
this .right = null ;
}
}
function newNode(key) {
var temp = new Node();
temp.key = key;
temp.left = temp.right = null ;
return (temp);
}
function inorder(root) {
if (root != null ) {
inorder(root.left);
document.write(root.key + " " );
inorder(root.right);
}
}
function createTree(parent , n) {
var m = new Map();
var root = new Node(), temp = new Node();
var i;
for (i = 0; i < n; i++) {
if (m.get(i) == null ) {
temp = newNode(i);
m.set(i, temp);
}
if (parent[i] == -1)
root = m.get(i);
else if (m.get(parent[i]) == null ) {
temp = newNode(parent[i]);
temp.left = m.get(i);
m.set(parent[i], temp);
}
else {
if (m.get(parent[i]).left == null )
m.get(parent[i]).left = m.get(i);
else
m.get(parent[i]).right = m.get(i);
}
}
return root;
}
var parent = [ -1, 0, 0, 1, 1, 3, 5 ];
var n = parent.length;
var root = createTree(parent, n);
document.write( "Inorder Traversal of constructed tree<br/>" );
inorder(root);
</script>
|
Output:
Inorder Traversal of constructed tree
6 5 3 1 4 0 2
Time complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(n), where n is the number of elements in the array.
Share your thoughts in the comments
Please Login to comment...