Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Diameter of Binary Tree

Medium Acceptance 73.45% Points 30

You are given the root of a binary tree. Your task is to find the diameter of the tree.

The diameter of a binary tree is defined as:

  • The length of the longest path between any two nodes in the tree.
  • The length is measured by the number of edges on that path.
  • The path may or may not pass through the root node.

Return the diameter of the binary tree.

Examples
Example 1

image Input: root = [1,2,3,4,5]
Output: 3
Explanation: The longest path is 4 → 2 → 1 → 3, which contains 3 edges.

Example 2

image Input: root = [1,2]
Output: 1
Explanation: The longest path connects the two nodes, resulting in a diameter of 1 edge.

Example 3

image Input: root = [1]
Output: 0
Explanation: A single-node tree has no edges, so its diameter is 0.

Constraints
    • 0 = Number of nodes = 105
    • -10? = Node.data = 10?
Topics
Tree Traversal Binary Tree
Companies
Infosys Rubrik
Added 03 Aug 2026 73.45% acceptance
Ln 1, Col 1Sign in to save your code
1
0