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 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Diameter of n-ary tree using BFS
- Diameter of a tree using DFS
- Diameter of a Binary Tree
- DP on Trees | Set-3 ( Diameter of 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
- Diameter of a Binary Indexed Tree with N nodes
- Finding the lexicographically smallest diameter in a binary tree
- Make a tree with n vertices , d diameter and at most vertex degree k
- 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
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Convert a given Binary tree to a tree that holds Logical OR property
- Check if a given Binary Tree is height balanced like a Red-Black Tree
- Convert a given Binary tree to a tree that holds Logical AND property
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
Improved By : Rajput-Ji