Skip to main content
Back to problems
Leetcode
Medium
Trees
Recursion
Tree DP
Google
Meta
Diameter Of Binary Tree

Find the length of the longest path between any two nodes in a binary tree.

Acceptance 0%
Problem Statement

Diameter of a Binary Tree

Given the root of a binary tree, compute its diameter.

The diameter is the length of the longest path between any two nodes in the tree. The path does not need to pass through the root.

For this problem, the length of a path is measured by the number of edges on that path.

Input Format

  • A binary tree root is provided as the input.
  • Each node contains an integer value, but the values are not relevant to the answer.

Output Format

  • Return a single integer: the diameter of the tree, measured in number of edges.

Constraints

  • The tree contains at least 1 node.
  • The tree is binary and finite.
  • Node values may be any integers.
  • A correct solution should run in linear time with respect to the number of nodes.
Examples
Sample cases returned by the problem API.

Example 1

Input

root = [1,2,3,4,5]

Output

3

Explanation

The longest path is 4 -> 2 -> 1 -> 3 or 5 -> 2 -> 1 -> 3, which has 3 edges.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.