So, the first way to represent a binary tree is by using arrays. We call this 'array representation'. And this method is not very recommended for representing binary trees. We'll know it shortly
Anywars, we will use an array to represent a binary tree. Suppose we have a binary tree with 7
nodes.
And there are actually a number of ways to represent these nodes via an array. I’ll use the most
convenient one where we traverse each level starting from the root node and from left to right and
mark them with the indices these nodes would belong to.
And now we can simply make an array of length 7 and store these elements at their corresponding
indices.
And you might be wondering about the cases where the binary is just not perfect. What if the
last level has distributed leaves? Then let me tell you, there is a way out for that as well. Let’s
consider one case here. A binary tree with 9 nodes, and the last two nodes on the extremities of the
last level.
Here, while traversing we get stuck at the 8th index. We don’t know if declaring the last node
as the 8th index element makes it a general representation of the tree or not. So, we simply make
the tree perfect ourselves. We first assume the remaining vacant places to be NULL.
And now we can easily mark their indices from 0 to 14.
And the array representation of the tree looks something like this. It is an array of length 15.
Suppose we have a binary tree of 3 levels.
Definition of struct Node in C language
struct node{
int data;
struct node* left;
struct node* right;
};