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++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// A tree node
struct Node {
int key;
struct Node *left, *right;
};
// Utility function to create new Node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Utility function to perform
// inorder traversal of the tree
void inorder(Node* root)
{
if (root != NULL) {
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
}
// Function to construct a Binary Tree from parent array
Node* createTree(int parent[], int n)
{
// A map to keep track of all the nodes created.
// Key: node value; Value: Pointer to that Node
map<int, Node*> m;
Node *root, *temp;
int i;
// Iterate for all elements of the parent array.
for (i = 0; i < n; i++) {
// Node i does not exist in the map
if (m.find(i) == m.end()) {
// Create a new node for the current index
temp = newNode(i);
// Entry of the node in the map with
// key as i and value as temp
m[i] = temp;
}
// If parent is -1
// Current node i is the root
// So mark it as the root of the tree
if (parent[i] == -1)
root = m[i];
// Current node is not root and parent
// of that node is not created yet
else if (m.find(parent[i]) == m.end()) {
// Create the parent
temp = newNode(parent[i]);
// Assign the node as the
// left child of the parent
temp->left = m[i];
// Entry of parent in map
m[parent[i]] = temp;
}
// Current node is not root and parent
// of that node is already created
else {
// Left child of the parent doesn't exist
if (!m[parent[i]]->left)
m[parent[i]]->left = m[i];
// Right child of the parent doesn't exist
else
m[parent[i]]->right = m[i];
}
}
return root;
}
// Driver code
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
// Java implementation of the approach
import java.util.*;
class GFG
{
// A tree node
static class Node
{
int key;
Node left, right;
};
// Utility function to create new Node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to perform
// inorder traversal of the tree
static void inorder(Node root)
{
if (root != null)
{
inorder(root.left);
System.out.print( root.key + " ");
inorder(root.right);
}
}
// Function to construct a Binary Tree from parent array
static Node createTree(int parent[], int n)
{
// A map to keep track of all the nodes created.
// Key: node value; Value: Pointer to that Node
HashMap<Integer, Node> m=new HashMap<>();
Node root=new Node(), temp=new Node();
int i;
// Iterate for all elements of the parent array.
for (i = 0; i < n; i++)
{
// Node i does not exist in the map
if (m.get(i) == null)
{
// Create a new node for the current index
temp = newNode(i);
// Entry of the node in the map with
// key as i and value as temp
m.put(i, temp);
}
// If parent is -1
// Current node i is the root
// So mark it as the root of the tree
if (parent[i] == -1)
root = m.get(i);
// Current node is not root and parent
// of that node is not created yet
else if (m.get(parent[i]) == null)
{
// Create the parent
temp = newNode(parent[i]);
// Assign the node as the
// left child of the parent
temp.left = m.get(i);
// Entry of parent in map
m.put(parent[i],temp);
}
// Current node is not root and parent
// of that node is already created
else
{
// Left child of the parent doesn't exist
if (m.get(parent[i]).left == null)
m.get(parent[i]).left = m.get(i);
// Right child of the parent doesn't exist
else
m.get(parent[i]).right = m.get(i);
}
}
return root;
}
// Driver code
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);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python implementation of the approach
# A tree node
class Node:
def __init__(self):
self.key = 0
self.left = None
self.right = None
# Utility function to create new Node
def newNode(key: int) -> Node:
temp = Node()
temp.key = key
temp.left = None
temp.right = None
return temp
# Utility function to perform
# inorder traversal of the tree
def inorder(root: Node):
if root is not None:
inorder(root.left)
print(root.key, end=" ")
inorder(root.right)
# Function to construct a Binary Tree from parent array
def createTree(parent: list, n: int) -> Node:
# A map to keep track of all the nodes created.
# Key: node value; Value: Pointer to that Node
m = dict()
root = Node()
# Iterate for all elements of the parent array.
for i in range(n):
# Node i does not exist in the map
if i not in m:
# Create a new node for the current index
temp = newNode(i)
# Entry of the node in the map with
# key as i and value as temp
m[i] = temp
# If parent is -1
# Current node i is the root
# So mark it as the root of the tree
if parent[i] == -1:
root = m[i]
# Current node is not root and parent
# of that node is not created yet
elif parent[i] not in m:
# Create the parent
temp = newNode(parent[i])
# Assign the node as the
# left child of the parent
temp.left = m[i]
# Entry of parent in map
m[parent[i]] = temp
# Current node is not root and parent
# of that node is already created
else:
# Left child of the parent doesn't exist
if m[parent[i]].left is None:
m[parent[i]].left = m[i]
# Right child of the parent doesn't exist
else:
m[parent[i]].right = m[i]
return root
# Driver Code
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)
# This code is contributed by
# sanjeev2552
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
// A tree node
class Node
{
public int key;
public Node left, right;
};
// Utility function to create new Node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to perform
// inorder traversal of the tree
static void inorder(Node root)
{
if (root != null)
{
inorder(root.left);
Console.Write( root.key + " ");
inorder(root.right);
}
}
// Function to construct a Binary Tree from parent array
static Node createTree(int []parent, int n)
{
// A map to keep track of all the nodes created.
// Key: node value; Value: Pointer to that Node
Dictionary<int, Node> m = new Dictionary<int, Node>();
Node root = new Node(), temp = new Node();
int i;
// Iterate for all elements of the parent array.
for (i = 0; i < n; i++)
{
// Node i does not exist in the map
if (!m.ContainsKey(i))
{
// Create a new node for the current index
temp = newNode(i);
// Entry of the node in the map with
// key as i and value as temp
m.Add(i, temp);
}
// If parent is -1
// Current node i is the root
// So mark it as the root of the tree
if (parent[i] == -1)
root = m[i];
// Current node is not root and parent
// of that node is not created yet
else if (!m.ContainsKey(parent[i]))
{
// Create the parent
temp = newNode(parent[i]);
// Assign the node as the
// left child of the parent
temp.left = m[i];
// Entry of parent in map
m.Add(parent[i], temp);
}
// Current node is not root and parent
// of that node is already created
else
{
// Left child of the parent doesn't exist
if (m[parent[i]].left == null)
m[parent[i]].left = m[i];
// Right child of the parent doesn't exist
else
m[parent[i]].right = m[i];
}
}
return root;
}
// Driver code
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);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript implementation of the approach
// A tree node
class Node {
constructor(val) {
this.key = val;
this.left = null;
this.right = null;
}
}
// Utility function to create new Node
function newNode(key) {
var temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Utility function to perform
// inorder traversal of the tree
function inorder(root) {
if (root != null) {
inorder(root.left);
document.write(root.key + " ");
inorder(root.right);
}
}
// Function to construct a Binary Tree from parent array
function createTree(parent , n) {
// A map to keep track of all the nodes created.
// Key: node value; Value: Pointer to that Node
var m = new Map();
var root = new Node(), temp = new Node();
var i;
// Iterate for all elements of the parent array.
for (i = 0; i < n; i++) {
// Node i does not exist in the map
if (m.get(i) == null) {
// Create a new node for the current index
temp = newNode(i);
// Entry of the node in the map with
// key as i and value as temp
m.set(i, temp);
}
// If parent is -1
// Current node i is the root
// So mark it as the root of the tree
if (parent[i] == -1)
root = m.get(i);
// Current node is not root and parent
// of that node is not created yet
else if (m.get(parent[i]) == null) {
// Create the parent
temp = newNode(parent[i]);
// Assign the node as the
// left child of the parent
temp.left = m.get(i);
// Entry of parent in map
m.set(parent[i], temp);
}
// Current node is not root and parent
// of that node is already created
else {
// Left child of the parent doesn't exist
if (m.get(parent[i]).left == null)
m.get(parent[i]).left = m.get(i);
// Right child of the parent doesn't exist
else
m.get(parent[i]).right = m.get(i);
}
}
return root;
}
// Driver code
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);
// This code contributed by umadevi9616
</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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read