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
Input: root = [1,2,3,4,5]
Output: 3
Explanation: The longest path is 4 → 2 → 1 → 3, which contains 3 edges.
Example 2
Input: root = [1,2]
Output: 1
Explanation: The longest path connects the two nodes, resulting in a diameter of 1 edge.
Example 3
Input: root = [1]
Output: 0
Explanation: A single-node tree has no edges, so its diameter is 0.
Constraints
- 0 = Number of nodes = 105
Topics
Tree Traversal Binary Tree
Track your submissions
Please log in to review your progress and explore code submissions from other participants.
Unlock the full solution
Please log in to access detailed answers and explanations.
Join the discussion
Please log in to join conversations with other participants.