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.
- Diameter of n-ary tree using BFS
- Diameter of an N-ary tree
- DP on Trees | Set-3 ( Diameter of N-ary Tree )
- Diameter of a Binary Tree
- Diameter of a Binary Tree in O(n) [A new method]
- Possible edges of a tree for given diameter, height and vertices
- Diameter of a Binary Indexed Tree with N nodes
- Make a tree with n vertices , d diameter and at most vertex degree k
- Finding the lexicographically smallest diameter in a binary tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
Improved By : princiraj1992