![]() |
VOOZH | about |
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.
Example 1:
Example 2:
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:
Implementation:
7
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.
Implementation:
Output
7
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
Node: Adjacency List has been used to store the Tree.
Below is the implementation of the above approach:
Diameter of tree is : 4