Diameter of an N-ary tree
The diameter of an N-ary tree is the longest path present between any two nodes of the tree. These two nodes must be two leaf nodes. The following examples have the longest path[diameter] shaded.
Prerequisite: Diameter of a binary tree.
The path can either start from one of the nodes and go up to one of the LCAs of these nodes and again come down to the deepest node of some other subtree or can exist as a diameter of one of the child of the current node.
The solution will exist in any one of these:
- Diameter of one of the children of the current node
- Sum of Height of the highest two subtree + 1
Optimizations to above solution: We can find diameter without calculating depth of the tree making small changes in the above solution, similar to finding diameter of binary tree.
A different optimized solution: Longest path in an undirected tree
Another Approach to get diameter using DFS in one traversal:
The diameter of a tree can be calculated as for every node
- The current node isn’t part of diameter (i.e Diameter lies on one of the children of the current node).
- The current node is part of diameter (i.e Diameter passes through the current node).
Node: Adjacency List has been used to store the Tree.
Below is the implementation of the above approach:
Diameter of tree is : 4
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.