Skip to main content

Diameter of N-Ary Tree - Solution & Explanation

MediumPremiumFree on FleetCodeTreeDepth-First Search6 min readAsked at: Goldman Sachs, Meta, Salesforce
Practice this problem

Problem Statement

Given a root of an N-ary tree, you need to compute the length of the diameter of the tree.

The diameter of an N-ary tree is the length of the longest path between any two nodes in the tree. This path may or may not pass through the root.

(Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value.)

 

Example 1:

Input: root = [1,null,3,2,4,null,5,6]
Output: 3
Explanation: Diameter is shown in red color.

Example 2:

Input: root = [1,null,2,null,3,4,null,5,null,6]
Output: 4

Example 3:

Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: 7

 

Constraints:

  • The depth of the n-ary tree is less than or equal to 1000.
  • The total number of nodes is between [1, 104].

Approach Overview

Problem Overview: Given the root of an N-ary tree, return the diameter of the tree. The diameter is the length of the longest path between any two nodes in the tree. The path may or may not pass through the root, and the length is measured by the number of edges.

Approach 1: Brute Force Height Recalculation (O(n²) time, O(h) space)

A straightforward idea is to treat every node as a potential “center” of the diameter. For each node, compute the heights of all its children and take the two largest heights to form a candidate diameter passing through that node. The problem is that height computation itself requires a recursive traversal of the subtree. If you recompute heights repeatedly for many nodes, the total work becomes O(n²) in the worst case. Space complexity is O(h) for recursion depth, where h is the tree height. This approach works for small trees but scales poorly.

Approach 2: Convert to Graph + Double BFS (O(n) time, O(n) space)

A tree diameter can also be found using two BFS passes. First convert the tree into an undirected graph representation by adding edges between each node and its children. Run BFS from an arbitrary node to find the farthest node A. Then run BFS again from A to find the farthest node from it; the distance between them is the diameter. Each BFS processes every node and edge once, giving O(n) time and O(n) space. This approach is conceptually simple but requires building an adjacency list and queue traversal.

Approach 3: DFS Tracking Top Two Heights (O(n) time, O(h) space)

The optimal solution performs a single depth-first search. For each node, compute the height of its subtree while also updating a global diameter. During DFS, iterate through all children and collect the two largest child heights. If the largest heights are h1 and h2, the longest path passing through the current node is h1 + h2. Update the global maximum with this value. The height returned to the parent is 1 + max(h1, h2, ...), effectively the longest downward path.

Each node is visited exactly once and each child edge is processed once, so the time complexity is O(n). The recursion stack uses O(h) space where h is the height of the tree. This technique is a classic tree DP pattern and appears frequently in diameter-style problems across tree and DFS questions.

Recommended for interviews: The DFS approach that tracks the top two child heights is the expected solution. Interviewers want to see that you recognize the diameter property: the longest path through a node equals the sum of its two deepest child paths. Discussing the brute force idea first shows you understand the definition of diameter, while implementing the single-pass DFS demonstrates algorithmic optimization and clean recursive reasoning.

Solution

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Height RecalculationO(n²)O(h)For conceptual understanding of how diameter is formed through a node
Graph Conversion + Double BFSO(n)O(n)When treating the tree as an undirected graph or when BFS is preferred
DFS Tracking Top Two HeightsO(n)O(h)Optimal approach for interviews and production tree traversal problems

Video Solution

Bottom-up | Leetcode-1522 | Diameter of N-Ary Tree • Imran Sarwar • 2,361 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Diameter of N-Ary Tree easy or hard?
Diameter of N-Ary Tree is considered a Medium problem. The challenge is recognizing that the longest path through a node depends on the top two child heights and implementing the DFS efficiently without recomputing subtree heights.
Diameter of N-Ary Tree Python/Java solution
Implement a DFS function that returns the height of each node's subtree. During traversal, maintain the two largest child heights and update a global diameter variable. This pattern works cleanly in Python, Java, C++, and Go using recursion.
How to solve Diameter of N-Ary Tree in O(n)?
Perform a depth-first search and compute subtree heights while traversing. For each node, track the two largest heights among its children. Update a global diameter using their sum, and return the maximum height plus one to the parent.
What is the best approach for Diameter of N-Ary Tree?
The best approach is a single-pass DFS that tracks the two largest child heights at every node. The diameter through a node equals the sum of its two deepest child paths. Updating a global maximum during traversal gives the final diameter in O(n) time with O(h) recursion space.
Is Diameter of N-Ary Tree asked at Google/Amazon/Meta?
Tree diameter problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants include binary tree diameter, weighted tree diameter, and general tree longest path questions that test DFS and tree DP patterns.
What data structure is used in Diameter of N-Ary Tree?
The problem uses an N-ary tree structure where each node contains a list of children. The algorithm relies on depth-first search traversal and recursion to compute subtree heights and update the global diameter.
What is the time complexity of Diameter of N-Ary Tree?
The optimal DFS solution runs in O(n) time because each node and edge is visited exactly once. The recursion stack uses O(h) space, where h is the height of the tree. In the worst case of a skewed tree, h can be O(n).

Ready to solve this problem?

Practice Diameter of N-Ary Tree with our built-in code editor and test cases.

Practice on FleetCode