With the help of an example, explain how a binary tree can be represented using an array.
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.
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++
- Java
- C#
- Python3
Can't set child at 3 , no parent found Can't set child at 4 , no parent found A-C---F---
Time complexity: O(log n) since using heap to create a binary tree
Space complexity: O(n) for array
Tirthankar Pal
MBA from IIT Kharagpur with GATE, GMAT, IIT Kharagpur Written Test, and Interview
2 year PGDM (E-Business) from Welingkar, Mumbai
4 years of Bachelor of Science (Hons) in Computer Science from the National Institute of Electronics and Information Technology
Google and Hubspot Certification
Brain Bench Certification in C++, VC++, Data Structure and Project Management
10 years of Experience in Software Development out of that 6 years 8 months in Wipro
Selected in Six World Class UK Universities:-
King's College London, Durham University, University of Exeter, University of Sheffield, University of Newcastle, University of Leeds
No comments:
Post a Comment