Tree: Implementation

Tree: Implementation

Hello everyone, I hope you are doing extremely well and learning from the tree series, In this blog, I shall be discussing with you the implementation of the tree data structure using an adjacency list and adjacency matrix.

Implementation using adjacency list

First of all, let's revise the definition of trees, the tree is a special graph having N nodes and N-1 edges.

Implementing trees is the same as implementing graphs, so learn to implement trees you will learn to implement graphs as well.

Let's implement trees using an adjacency list:

The adjacency list which stores 5 nodes numbered from 0 to 4 can be declared as follows:


Then, the next question is how can we store the nodes in it, Let's see how can we do so.

Let's see how can we make edges

//Here, I am making a bidirectional edge

//Here, again a bidirectional edge between 1 and 3

//Bidirectional edge between 2 and 0

//Bidirectional edge between 1 and 4

The edges above are bidirectional i.e. both ways and hence, we need to make edges both ways:)

So that's all I have got for this, will see you in my next blog :D