VOOZH about

URL: https://www.geeksforgeeks.org/dsa/diameter-n-ary-tree/

⇱ Diameter of an N-ary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Diameter of an N-ary tree

Last Updated : 27 Mar, 2024

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:

👁 diameternary


Example 2:

👁 diameterN2

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: 

  1. Diameter of one of the children of the current node 
  2.  Sum of Height of the highest two subtree + 1 

Implementation:


Output
7
  • Time Complexity : O( N )
  • Space Complexity : O( N )

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
  • Time Complexity: O(N^2)
  • Auxiliary Space: O(N+H) where N is the number of nodes in tree and H is the height of the 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:


Output
Diameter of tree is : 4
  • Time Complexity: O(N), Where N is the number of nodes in given binary tree.
  • Auxiliary Space: O(N)
Comment
Article Tags:
Article Tags: