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. Do refer in order to understand how to construct binary tree from given parent array representation.
Ways to represent:Â
Trees can be represented in two ways as listed below:
- Dynamic Node Representation (Linked Representation).
- Array Representation (Sequential Representation).
Now, we are going to talk about the sequential representation of the trees. In order to represent a tree using an array, the numbering of nodes can start either from 0–(n-1) or 1– n, consider the below illustration as follows:
Illustration:
A(0)
/ \
B(1) C(2)
/ \ \
D(3) E(4) F(6)
OR,
A(1)
/ \
B(2) C(3)
/ \ \
D(4) E(5) F(7)
Procedure:
Note: father, left_son and right_son are the values of indices of the array.
 Case 1: (0—n-1)Â
if (say)father=p;Â then left_son=(2*p)+1;Â and right_son=(2*p)+2;
Case 2: 1—n
if (say)father=p;Â then left_son=(2*p);Â and right_son=(2*p)+1;Â
Implementation:
C++
// C++ implementation of tree using array// numbering starting from 0 to n-1.#include<bits/stdc++.h>using namespace std;char tree[10];int root(char key) {  if (tree[0] != '\0')    cout << "Tree already had root";  else    tree[0] = key;  return 0;}Â
int set_left(char key, int parent) {  if (tree[parent] == '\0')    cout << "\nCan't set child at "    << (parent * 2) + 1    << " , no parent found";  else    tree[(parent * 2) + 1] = key;  return 0;}Â
int set_right(char key, int parent) {  if (tree[parent] == '\0')    cout << "\nCan't set child at "    << (parent * 2) + 2    << " , no parent found";  else    tree[(parent * 2) + 2] = key;  return 0;}Â
int print_tree() {  cout << "\n";  for (int i = 0; i < 10; i++) {    if (tree[i] != '\0')      cout << tree[i];    else      cout << "-";  }  return 0;}Â
// Driver Codeint main() {Â Â root('A');Â Â set_left('B',0);Â Â set_right('C', 0);Â Â set_left('D', 1);Â Â set_right('E', 1);Â Â set_right('F', 2);Â Â print_tree();Â Â return 0;} |
Java
// JAVA implementation of tree using array// numbering starting from 0 to n-1.Â
// Importing required classesimport java.io.*;import java.lang.*;import java.util.*;Â
// Class 1// Helper class (Node class)public class Tree {Â
    // Main driver method    public static void main(String[] args)    {Â
        // Creating object of class 2 inside main() method        Array_imp obj = new Array_imp();Â
        // Setting root node        obj.Root("A");        obj.set_Left("B", 0);        obj.set_Right("C", 0);        obj.set_Left("D", 1);        obj.set_Right("E", 1);        obj.set_Right("F", 2);        obj.print_Tree();    }}Â
// Class 2// Helper classclass Array_imp {Â
    // Member variables of this class    static int root = 0;    static String[] str = new String[10];Â
    // Method 1    // Creating root node    public void Root(String key) { str[0] = key; }Â
    // Method 2    // Creating left son of root    public void set_Left(String key, int root)    {        int t = (root * 2) + 1;Â
        if (str[root] == null) {            System.out.printf(                "Can't set child at %d, no parent found\n",                t);        }        else {            str[t] = key;        }    }Â
    // Method 3    // Creating right son of root    public void set_Right(String key, int root)    {        int t = (root * 2) + 2;Â
        if (str[root] == null) {            System.out.printf(                "Can't set child at %d, no parent found\n",                t);        }        else {            str[t] = key;        }    }Â
    // Method 4    // To print our tree    public void print_Tree()    {Â
        // Iterating using for loop        for (int i = 0; i < 10; i++) {            if (str[i] != null)                System.out.print(str[i]);            else                System.out.print("-");        }    }} |
C#
// C# implementation of tree using array// numbering starting from 0 to n-1.using System;Â
public class Tree {Â Â Â Â public static void Main(String[] args)Â Â Â Â {Â Â Â Â Â Â Â Â Array_imp obj = new Array_imp();Â Â Â Â Â Â Â Â obj.Root("A");Â Â Â Â Â Â Â Â obj.set_Left("B", 0);Â Â Â Â Â Â Â Â obj.set_Right("C", 0);Â Â Â Â Â Â Â Â obj.set_Left("D", 1);Â Â Â Â Â Â Â Â obj.set_Right("E", 1);Â Â Â Â Â Â Â Â obj.set_Right("F", 2);Â Â Â Â Â Â Â Â obj.print_Tree();Â
    }}Â
class Array_imp {Â Â Â Â static int root = 0;Â Â Â Â static String[] str = new String[10];Â
    /*create root*/    public void Root(String key)    {        str[0] = key;    }Â
    /*create left son of root*/    public void set_Left(String key, int root)    {        int t = (root * 2) + 1;Â
        if (str[root] == null) {            Console.Write("Can't set child at {0}, no parent found\n", t);        }        else {            str[t] = key;        }    }Â
    /*create right son of root*/    public void set_Right(String key, int root)    {        int t = (root * 2) + 2;Â
        if (str[root] == null) {            Console.Write("Can't set child at {0}, no parent found\n", t);        }        else {            str[t] = key;        }    }Â
    public void print_Tree()    {        for (int i = 0; i < 10; i++) {            if (str[i] != null)                Console.Write(str[i]);            else                Console.Write("-");        }    }}Â
// This code contributed by Rajput-Ji |
Python3
# Python3 implementation of tree using array# numbering starting from 0 to n-1.tree = [None] * 10Â
Â
def root(key):Â Â Â Â if tree[0] != None:Â Â Â Â Â Â Â Â print("Tree already had root")Â Â Â Â else:Â Â Â Â Â Â Â Â tree[0] = keyÂ
Â
def set_left(key, parent):Â Â Â Â if tree[parent] == None:Â Â Â Â Â Â Â Â print("Can't set child at", (parent * 2) + 1, ", no parent found")Â Â Â Â else:Â Â Â Â Â Â Â Â tree[(parent * 2) + 1] = keyÂ
Â
def set_right(key, parent):Â Â Â Â if tree[parent] == None:Â Â Â Â Â Â Â Â print("Can't set child at", (parent * 2) + 2, ", no parent found")Â Â Â Â else:Â Â Â Â Â Â Â Â tree[(parent * 2) + 2] = keyÂ
Â
def print_tree():Â Â Â Â for i in range(10):Â Â Â Â Â Â Â Â if tree[i] != None:Â Â Â Â Â Â Â Â Â Â Â Â print(tree[i], end="")Â Â Â Â Â Â Â Â else:Â Â Â Â Â Â Â Â Â Â Â Â print("-", end="")Â Â Â Â print()Â
Â
# Driver Coderoot('A')set_left('B', 0)set_right('C', 0)set_left('D', 1)set_right('E', 1)set_right('F', 2)print_tree()Â
Â
Â
# This code is contributed by Gaurav Kumar Tailor |
Javascript
// JavaScript implementation of tree using array// numbering starting from 0 to n-1.const tree = Array(10).fill(null);Â
function root(key) {Â Â Â Â if (tree[0] != null) {Â Â Â Â Â Â Â Â console.log("Tree already had root");Â Â Â Â } else {Â Â Â Â Â Â Â Â tree[0] = key;Â Â Â Â }}Â
function setLeft(key, parent) {Â Â Â Â if (tree[parent] == null) {Â Â Â Â Â Â Â Â console.log(`Can't set child at ${(parent * 2) + 1}, no parent found <br>`);Â Â Â Â } else {Â Â Â Â Â Â Â Â tree[(parent * 2) + 1] = key;Â Â Â Â }}Â
function setRight(key, parent) {Â Â Â Â if (tree[parent] == null) {Â Â Â Â Â Â Â Â console.log(`Can't set child at ${(parent * 2) + 2}, no parent found <br>`);Â Â Â Â } else {Â Â Â Â Â Â Â Â tree[(parent * 2) + 2] = key;Â Â Â Â }}Â
function printTree() {Â Â Â Â for (let i = 0; i < 10; i++) {Â Â Â Â Â Â Â Â if (tree[i] != null) {Â Â Â Â Â Â Â Â Â Â Â Â console.log(tree[i]);Â Â Â Â Â Â Â Â } else {Â Â Â Â Â Â Â Â Â Â Â Â console.log("-");Â Â Â Â Â Â Â Â }Â Â Â Â }}Â
// Driver Coderoot("A");setLeft("B", 0);setRight("C", 0);setLeft("D", 1);setRight("E", 1);setRight("F", 2);printTree();Â
Â
Â
// This code is contributed by lokeshpotta20 |
ABCDE-F---
Time complexity: O(log n) since using heap to create a binary tree
Space complexity: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
