Problem Statement
Diameter of Binary Tree
You are given the root of a binary tree. A binary tree is a structure where each box (called a node) holds a value and points to up to two child boxes below it, a left child and a right child. Your job is to find the diameter of the tree. The diameter is the length of the longest path between any two nodes, measured by counting the edges (the connecting lines) along that path. This longest path may go through the root, or it may live entirely in some lower part of the tree.
Signals to notice
Brute force first
For each node, compute depths of both subtrees — because depth computation is and you repeat for every node. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.
The key insight
DFS returning depth, but at each node also compute the diameter THROUGH that node (left depth + right depth). Track the global maximum. — one pass. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
Trace it on root = [1,2,3,4,5] (1->L:2,R:3; 2->L:4,R:5)
dfs(4): no children -> L=0,R=0; diameter=max(0,0)=0; return 1 dfs(5): no children -> L=0,R=0; diameter=max(0,0)=0; return 1 dfs(2): L=dfs(4)=1, R=dfs(5)=1; diameter=max(0,1+1)=2; return 1+max(1,1)=2 dfs(3): no children -> L=0,R=0; diameter=max(2,0)=2; return 1 dfs(1): L=dfs(2)=2, R=dfs(3)=1; diameter=max(2,2+1)=3; return 1+max(2,1)=3 dfs(root) done -> return diameter = 3
What must stay true
The diameter through any node = leftDepth + rightDepth. The overall diameter is the maximum across all nodes. Each DFS call returns depth (for its parent) while also checking diameter (for the global answer). As long as that statement keeps holding, you can trust the steps built on top of it.
Shape of the loop
function dfs(node):
if node is null: return 0
L = dfs(node.left); R = dfs(node.right)
diameter = max(diameter, L + R) // path THROUGH this node
return 1 + max(L, R) // depth for parent
dfs(root); return diameterPseudocode only — the full worked solution lives in the Solution tab.
Easy way to go wrong
Only checking the diameter through the root — the longest path might not pass through the root at all. You must check every node. The fix is usually to return to the meaning of each move, not just the steps themselves.