> ## 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.

# Tree Diameter Python Solution with Tests

> Tested Python solution for LeetCode 1245 with 25 pytest cases. Generate a practice environment with lcpy.

LeetCode 1245, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Graph](/catalog/topics/graph), [Topological Sort](/catalog/topics/topological-sort). [View on LeetCode](https://leetcode.com/problems/tree-diameter/description/).

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

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

## Problem

The **diameter** of a tree is **the number of edges** in the longest path in that tree.

There is an undirected tree of `n` nodes labeled from `0` to `n - 1`. You are given a 2D array `edges` where `edges.length == n - 1` and `edges[i] = [ai, bi]` indicates that there is an undirected edge between nodes `ai` and `bi` in the tree.

Return **the diameter** of the tree.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1200-1299/1245.Tree%20Diameter/images/tree1.jpg)

```
Input: edges = [[0,1],[0,2]]
Output: 2
```

**Explanation:** The longest path of the tree is the path 1 - 0 - 2.

![Example 2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1200-1299/1245.Tree%20Diameter/images/tree2.jpg)

```
Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
Output: 4
```

**Explanation:** The longest path of the tree is the path 3 - 2 - 1 - 4 - 5.

### Constraints

* `n == edges.length + 1`
* `1 <= n <= 10^4`
* `0 <= ai, bi < n`
* `ai != bi`

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import defaultdict, deque


class Solution:
    # Time: O(n)
    # Space: O(n)
    def tree_diameter(self, edges: list[list[int]]) -> int:
        if not edges:
            return 0
        graph: dict[int, list[int]] = defaultdict(list)
        for a, b in edges:
            graph[a].append(b)
            graph[b].append(a)

        def bfs_farthest(src: int) -> tuple[int, int]:
            dist = {src: 0}
            queue: deque[int] = deque([src])
            far_node, far_dist = src, 0
            while queue:
                node = queue.popleft()
                for nxt in graph[node]:
                    if nxt not in dist:
                        dist[nxt] = dist[node] + 1
                        if dist[nxt] > far_dist:
                            far_dist = dist[nxt]
                            far_node = nxt
                        queue.append(nxt)
            return far_node, far_dist

        end, _ = bfs_farthest(edges[0][0])
        _, diameter = bfs_farthest(end)
        return diameter
```

## Complexity

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

## Tags

[NeetCode All](/catalog/neetcode).


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