Back to Practice
#0277
Diameter of Binary Tree
MediumDSA28 min20 XP
Problem
A tree node is [value, left, right]. Return the diameter measured in edges.
Why This Matters
Diameter is the first tree problem where the answer may pass through a node while the return value is only one side depth.
Function Signature
def diameter(root):
Examples
Example 1
Inputroot = [1,[2,[4,None,None],[5,None,None]],[3,None,None]]
Output3
The longest path is 4 -> 2 -> 1 -> 3, which has 3 edges.
Constraints
- Return the exact requested value.
- Handle edge cases cleanly.
- Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Diameter through root
Inputclassic five-node tree
Expected3
Left depth 2 and right depth 1 combine at the root.
Single node
Input[1]
Expected0
One node has no edge path.
Hidden Test Categories
empty treediameter entirely inside one subtreelong chain