Binary Tree Representation in Data Structures

Here we will see how to represent a binary tree in computers memory. There are two different methods for representing. These are using array and using linked list.

Suppose we have one tree like this −

The array representation stores the tree data by scanning elements using level order fashion. So it stores nodes level by level. If some element is missing, it left blank spaces for it. The representation of the above tree is like below −


The index 1 is holding the root, it has two children 5 and 16, they are placed at location 2 and 3. Some children are missing, so their place is left as blank.

In this representation we can easily get the position of two children of one node by using this formula −



To get parent index from child we have to follow this formula −

$$parent=\begin{bmatrix}\frac{child}{2} \end{bmatrix}$$

This approach is good, and easily we can find the index of parent and child, but it is not memory efficient. It will occupy many spaces that has no use. This representation is good for complete binary tree or full binary tree.

Another approach is by using linked lists. We create node for each element. This will be look like below −