VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-tree-array-implementation/

⇱ Binary Tree (Array implementation) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Tree (Array implementation)

Last Updated : 6 Apr, 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. 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:


Output
ABCDE-F---

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

Comment
Article Tags: