VOOZH about

URL: https://www.geeksforgeeks.org/dsa/dp-on-trees-set-3-diameter-of-n-ary-tree/

⇱ DP on Trees | Set-3 ( Diameter of N-ary Tree ) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

DP on Trees | Set-3 ( Diameter of N-ary Tree )

Last Updated : 11 Jul, 2025

Given an N-ary tree, the task is to calculate the longest path between any two nodes (also known as the diameter of the tree).

Examples:

Example1: The diameter of the N-ary tree in the below example is 9, which represents the number of edges along the path marked with green nodes.

👁 diameter---------of---------a---------n---------array---------tree


Example2: The diameter of the N-ary tree in the below example is 7, which represents the number of edges along the path marked with green nodes.

👁 diameter---------of---------a---------n---------array---------tree---------2

Approach:

The idea is to use Dynamic Programming with two key states: dp1[node] and dp2[node]. The value dp1[node] represents the longest path from the current node to any leaf in its subtree, while dp2[node] represents the longest path passing through the current node and two of its subtrees. By combining these two states across all nodes, we compute the maximum diameter. A Depth First Search (DFS) traversal is used to calculate these states efficiently.

Step-by-step approach:

  • Use dp1[node] (longest path to a leaf in subtree) and dp2[node] (longest path passing through the node and its two subtrees).
  • For leaf nodes, set dp1[node] = 0 and dp2[node] = 0.
  • Begin a DFS traversal from an arbitrary node, tracking the parent to avoid revisits.
  • For each node, find the two largest dp1[child] values using firstMaxand secondMax.
  • Compute dp1[node] = 1 + firstMax and dp2[node] = firstMax + secondMax.
  • Update the diameter as the maximum of dp2[node] and the current diameter.

Output
3

Time Complexity: O(n), where n is the total number of nodes in the tree.
Auxiliary Space: O(n)

Related articles:

Comment
Article Tags: