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:

vector<int>tree[5];

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
tree[0].push_back(1);
tree[1].push_back(0);

//Here, again a bidirectional edge between 1 and 3
tree[1].push_back(3);
tree[3].push_back(1);

//Bidirectional edge between 2 and 0
tree[0].push_back(2);
tree[2].push_back(0);

//Bidirectional edge between 1 and 4
tree[1].push_back(4);
tree[4].push_back(1);

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