Diameter of a tree
Challenge · Write code · about 15 min
Given the root of a binary tree, return its diameter: the number of edges on the longest path between any two nodes. The path does not have to pass through the root. An empty tree or a single node has diameter 0.
Example 1
Input:
[[1,2,3,4,5]]
Output:
3
The path 4 → 2 → 1 → 3 has 3 edges. So does 5 → 2 → 1 → 3.
Example 2
Input:
[[1,2]]
Output:
1
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Recursive problems on trees: height, size, mirror, paths, a visual lesson.
More Recursive problems on trees: height, size, mirror, paths problems
- Who reports first? Warm-up
- Complete the node counter Warm-up
- Max depth Standard
- Invert a tree Standard
- Path sum Standard
- Same tree Standard
- Fix the height function Standard