The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree. The diagram below shows two trees each with diameter five, the leaves that form the ends of the longest path are shaded (note that there is more than one path in each tree of length five, but no path longer than five nodes)
We have discussed a solution in below post
In this post a different DFS based solution is discussed. After observing above tree we can see that the longest path will always occur between two leaf nodes. We start DFS from a random node and then see which node is farthest from it. Let the node farthest be X. It is clear that X will always be a leaf node and a corner of DFS. Now if we start DFS from X and check the farthest node from it, we will get the diameter of the tree.
The C++ implementation uses adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes.
Diameter of the given tree is 4
This article is contributed by Ankur Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Diameter of n-ary tree using BFS
- Diameter of a Binary Tree
- Diameter of an N-ary tree
- Diameter of a Binary Tree in O(n) [A new method]
- Possible edges of a tree for given diameter, height and vertices
- DP on Trees | Set-3 ( Diameter of N-ary Tree )
- Make a tree with n vertices , d diameter and at most vertex degree k
- Diameter of a Binary Indexed Tree with N nodes
- Finding the lexicographically smallest diameter in a binary tree
- DFS traversal of a tree using recursion
- Subtree of all nodes in a tree using DFS
- Level with maximum number of nodes using DFS in a N-ary tree
- Count the number of nodes at a given level in a tree using DFS
- Print all leaf nodes of an n-ary tree using DFS
- Construct the Rooted tree by using start and finish time of its DFS traversal
- Kth ancestor of all nodes in an N-ary tree using DFS
- BFS vs DFS for Binary Tree
- DFS for a n-ary tree (acyclic graph) represented as adjacency list
- Tree, Back, Edge and Cross Edges in DFS of Graph
- Find the Kth node in the DFS traversal of a given subtree in a Tree
Improved By : princiraj1992