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 node and goes 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:
I] Diameter of one of the children of the current node
II] Sum of Height of highest two subtree + 1
Optimizations to above solution :
We can make a hash table to store heights of all nodes. If we precompute these heights, we don’t need to call depthOfTree() for every node.
A different optimized solution :
Longest path in an undirected tree
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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 a Binary Tree
- Longest path in an undirected tree
- How to determine if a binary tree is height-balanced?
- Diameter of a Binary Tree in O(n) [A new method]
- Depth of an N-Ary tree
- HashSet vs TreeSet in Java
- Preorder from Inorder and Postorder traversals
- Count pairs in a binary tree whose sum is equal to a given value x
- Find the maximum node at a given level in a binary tree
- Print nodes in top view of Binary Tree | Set 2