You are given the root of a binary tree. The diameter is defined as the length of the longest path between any two nodes in the tree, measured by the number of edges on that path.
The path does not need to run through the root, and the two endpoints can be any pair of nodes. Return the diameter of the tree.
Example 1
Input: root = [1,2,3,4,5]
Output: 3
The longest path is 4 -> 2 -> 1 -> 3 (or 5 -> 2 -> 1 -> 3), which contains 3 edges.
Example 2
Input: root = [1,2]
Output: 1
The only path connecting two nodes is 1 -> 2, a single edge.
Constraints
The number of nodes in the tree is in the range [1, 10^4].-100 <= Node.val <= 100See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI