Tuesday, September 14, 2021

Diameter of a Tree

The diameter of a tree is the longest path between any two nodes of a given tree.

For a better understanding look at the picture, here the diameter is 6, why? Because if we take two nodes, '8' and '9' the distance will be maximum. There are no pairs whose distance is greater than (8,9) pair. So diameter is 6 in this case. See, we are considering edges, not vertices.

So, how can we calculate the diameter of a tree! Basically, we can solve it using BFS or DFS. Let's discuss it one by one.


Using DFS,

Suppose there are N nodes, every time we will take any nodes and run a dfs from this node(Assume chosen node is root), at the same time we will update maximum distance. 
In this case, the runtime will be O(n^2), n nodes, and every time a dfs.

So this is huge, can we optimize it? 
Yes, we can optimize it by using two(2) DFS.

First, we choose a root node ( say 1 ), we start our first dfs from the root node, suppose we got the deepest node is 'X'.
Second, we start another dfs from node 'X', and finally, we can get our desired answer( maximum distance aka diameter ).


Using BFS,
Same as before we did in dfs, again we will find any longest node Using First BFS and after that, we will start another BFS from this node. In BFS, Implementation is slightly different.

Related problems:

1. Tree Diameter - CSES 
2. PT07Z - Longest path in a tree-Spoj 
3. LOJ-1094
4. Diameter of a tree-Leetcode

For better understanding see the code given below,





No comments:

Post a Comment