Array Representation of Binary Tree
Array Representation of Binary Tree
Submitted By:
1.Ammar Jemal
2.Ahmed Hassen
3.Michael Daniel
4.Nahom Lulseged
B C
D E F G
H I
0 1 2 3 4 5 6 7 8
A B C D E F G H I
B C
D E F G
H I
0 1 2 3 4 5 6 7 8 9 10
A B C D E F G - - H I
Advantages
Implementation in C++
#include <iostream>
using namespace std;
const int SIZE = 11;
char BT[SIZE];
int root(char key){
if(BT[0] != '\0')
cout<<"Tree already has a root.";
else
BT[0] = key;
return 0;
}
int leftChild(char key, int parent){
if(BT[parent] == '\0')
cout <<"\nNo parent found";
else
BT[(parent * 2) + 1] = key;
return 0;
}
int rightChild(char key, int parent){
if(BT[parent] == '\0')
cout<<"\nNo parent found";
else
BT[(parent * 2) + 2] = key;
return 0;
}
int displayTree(){
cout << "\n";
for(int i = 0; i < SIZE; i++){
if(BT[i] != '\0')
cout<<BT[i]<<',';
else
cout<<"-"<<',';
}
return 0;
}
int main(){
root('A');
leftChild('B', 0);
rightChild('C', 0);
leftChild('D', 1);
rightChild('E', 1);
leftChild('F', 2);
rightChild('G', 2);
leftChild('H', 4);
rightChild('I', 4);
displayTree();
return 0;
}