Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Diameter of Binary Tree

Medium Acceptance 73.45% Points 30.00

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?
Companies
Infosys Rubrik
Topics
Tree Traversal Binary Tree
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions