> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Diameter of N-Ary Tree Python Solution

> Tested Python solution for LeetCode 1522 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 1522, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), Tree DP. [View on LeetCode](https://leetcode.com/problems/diameter-of-n-ary-tree/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1522   # by problem number
lcpy gen -s diameter_of_n_ary_tree   # by problem name
```

## Problem

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.)*

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/images/sample_2_1897.png)

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

![Example 2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/images/sample_1_1897.png)

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

![Example 3](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1500-1599/1522.Diameter%20of%20N-Ary%20Tree/images/sample_3_1897.png)

```
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, 10^4]`.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/diameter_of_n_ary_tree/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/diameter_of_n_ary_tree/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from __future__ import annotations


class NaryNode:
    def __init__(self, val: int = 0, children: list[NaryNode] | None = None) -> None:
        self.val = val
        self.children = children if children is not None else []


class Solution:
    # Time: O(n)
    # Space: O(h)
    def diameter(self, root: NaryNode | None) -> int:
        ans = 0

        def dfs(node: NaryNode | None) -> int:
            nonlocal ans
            if node is None:
                return 0
            first = second = 0
            for child in node.children:
                depth = dfs(child)
                if depth > first:
                    second, first = first, depth
                elif depth > second:
                    second = depth
            ans = max(ans, first + second)
            return 1 + first

        dfs(root)
        return ans
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(h) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.