Open In App

Binary Tree (Array implementation)

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Dynamic Node Representation (Linked Representation).
  2. 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 Code
int 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 classes
import 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 class
class 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 Code
root('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 Code
root("A");
setLeft("B", 0);
setRight("C", 0);
setLeft("D", 1);
setRight("E", 1);
setRight("F", 2);
printTree();
 
 
 
// This code is contributed by lokeshpotta20


Output

ABCDE-F---

Time complexity: O(log n) since using heap to create a binary tree
Space complexity: O(1)



Previous Article
Next Article

Similar Reads

Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtrees after traversing the subtrees. Follow
15+ min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Implementation of compressed 2D Binary Indexed tree
A compressed 2D Binary Indexed Tree (BIT) is a data structure that is used to efficiently store and query two-dimensional arrays, particularly when the values in the array are frequently updated. The compressed 2D Binary Indexed Tree (BIT) is a data structure used for fast querying and updating values in a two-dimensional array. It is an extension
15+ min read
Implementation of Binary Search Tree in Javascript
In this article, we would be implementing the Binary Search Tree data structure in Javascript. A tree is a collection of nodes connected by some edges. A tree is a non linear data structure. A Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right.
9 min read
Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
Given a binary tree, the task is to print the maximum sum of nodes of a sub-tree which is also a Binary Search Tree.Examples: Input : 7 / \ 12 2 / \ \ 11 13 5 / / \ 2 1 38 Output:44 BST rooted under node 5 has the maximum sum 5 / \ 1 38 Input: 5 / \ 9 2 / \ 6 3 / \ 8 7 Output: 8 Here each leaf node represents a binary search tree also a BST with su
12 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree.This solution will use Sets of C++ STL instead of array-based solution. Examples: Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \
12 min read