Full answer
Problem
Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes.
Example: 1 -> (2 -> 4, 5), 3 has diameter 3 (the path 4, 2, 1, 3). In 1 -> (2 -> (3 -> 4), (5 -> -, 6)) the longest path is 4, 3, 2, 5, 6 with 4 edges, and it does not touch the root.
Constraints: 1 to 10^4 nodes.
Brute force
For each node, compute the height of its left and right subtrees separately and take the best left + right over all nodes. Each height call is O(n), so the total is O(n^2) on a chain.
Optimal approach
One post-order DFS where height(node) returns the number of nodes on the longest downward path. At each node, after getting lh and rh, update best = max(best, lh + rh) and return 1 + max(lh, rh).
Why it works
Every path in a tree has exactly one highest node, where it bends. The longest path bending at a node goes down the deepest branch on each side, so its edge count is lh + rh when heights count nodes. Checking every node as the bend point covers every path, and computing heights bottom-up means each is computed once.
Complexity
O(n) time, O(h) recursion space.
Code
import random
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def diameter(root):
"""Longest path (in edges) between any two nodes. One post-order pass, O(n)."""
best = 0
def height(node): # number of nodes on the longest downward path
nonlocal best
if node is None:
return 0
lh, rh = height(node.left), height(node.right)
best = max(best, lh + rh) # path that bends at this node
return 1 + max(lh, rh)
height(root)
return best
def brute(root):
"""O(n^2): for each node, recompute heights of both subtrees."""
def h(n):
return 0 if n is None else 1 + max(h(n.left), h(n.right))
def walk(n):
if n is None:
return 0
return max(h(n.left) + h(n.right), walk(n.left), walk(n.right))
return walk(root)
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.3:
return None
return TreeNode(0, random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
assert diameter(t) == 3 # 4 -> 2 -> 1 -> 3
assert diameter(None) == 0 and diameter(TreeNode(1)) == 0
# longest path does not pass through the root
side = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4)), TreeNode(5, None, TreeNode(6))))
assert diameter(side) == 4
rng = random.Random(56)
for _ in range(2000):
r = random_tree(rng, 6)
assert diameter(r) == brute(r)
print("all tests passed")Save as b56_diameter.py and run python3 b56_diameter.py. It prints all tests passed (Python 3.13.5).
Edge cases
Empty tree or single node: diameter 0. A chain: diameter n - 1. The path does not pass through the root (covered by the second example). Be explicit about edges versus nodes; some versions count nodes, which is one more.
Pattern
Return one value to the parent (height) while updating a global answer from both children (the bend). The same structure solves binary tree maximum path sum, longest univalue path, and tree diameter in graphs (or two BFS passes in an unweighted tree).
import random
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def diameter(root):
"""Longest path (in edges) between any two nodes. One post-order pass, O(n)."""
best = 0
def height(node): # number of nodes on the longest downward path
nonlocal best
if node is None:
return 0
lh, rh = height(node.left), height(node.right)
best = max(best, lh + rh) # path that bends at this node
return 1 + max(lh, rh)
height(root)
return best
def brute(root):
"""O(n^2): for each node, recompute heights of both subtrees."""
def h(n):
return 0 if n is None else 1 + max(h(n.left), h(n.right))
def walk(n):
if n is None:
return 0
return max(h(n.left) + h(n.right), walk(n.left), walk(n.right))
return walk(root)
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.3:
return None
return TreeNode(0, random_tree(rng, depth - 1), random_tree(rng, depth - 1))
if __name__ == "__main__":
t = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))
assert diameter(t) == 3 # 4 -> 2 -> 1 -> 3
assert diameter(None) == 0 and diameter(TreeNode(1)) == 0
# longest path does not pass through the root
side = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4)), TreeNode(5, None, TreeNode(6))))
assert diameter(side) == 4
rng = random.Random(56)
for _ in range(2000):
r = random_tree(rng, 6)
assert diameter(r) == brute(r)
print("all tests passed")One post-order pass with a nonlocal best, cross-checked against the O(n^2) version on random trees.
Complexity
Time: O(n). Space: O(h). For a general unweighted tree stored as a graph, two BFS passes (farthest from any node, then farthest from that) also give the diameter in O(n).
By level
Fresher: Explains that the longest path bends at some node and computes it with a height helper. Shows a tree where the answer avoids the root.
Mid: Writes the single-pass version with a running maximum and separates the returned value from the answer. Extends it to the weighted maximum path sum.
Senior: Generalizes to trees given as edge lists with the two-BFS argument and explains why it works only for trees. Discusses iterative post-order to avoid recursion limits on deep inputs.
Key points
- Each path bends at exactly one highest node
- Path through a node = left height + right height
- Return height, update the global best
- O(n) by computing heights once
- Clarify edges versus nodes
Common mistakes
- Returning the diameter from the recursion instead of the height
- Only checking the path through the root
- Off-by-one between edges and nodes
- Recomputing heights for every node
Follow-ups
- How do you find the maximum path sum when nodes have weights?
- How would you find the diameter of a general tree given as an edge list?
- How do you return the actual path, not just its length?
Tips
- Draw a tree where the diameter avoids the root
- Say clearly what the helper returns
- Mention the two-BFS method for general trees
Evaluation rubric
- Correct single-pass algorithm
- Handles paths not through the root
- Correct unit (edges)
- Correct complexity