Data Structures · Visualization
Binary Tree: Diameter
Binary Tree
The diameter of a tree is the length of the longest path between any two nodes, and that path might not pass through the root. Time: O(n) with the optimized single-pass approach. Space: O(h) for the recursion stack.
Big-O: Traversals visit every node exactly once: O(n).
Binary Tree: Diameter
Binary TreeThe diameter of a tree is the length of the longest path between any two nodes, and that path might not pass through the root. It is computed by, at every node, considering the path that goes through it (left subtree height + right subtree height), and keeping track of the maximum such value seen anywhere in the tree.
How Diameter Works
- Define a recursive height function that also updates a running 'best diameter' value.
- For each node, recursively compute the height of its left and right subtrees.
- Compute the path length through this node: left height + right height.
- Update the running maximum diameter if this path is longer than any seen so far.
- Return this node's own height (1 + max of the two subtree heights) up to its parent.
Diameter Worked Example
Input: Tree: root(1) -> left(2) -> left(3); root -> right(4)
- At node 3 (leaf): height 0, path through it = 0
- At node 2: left height 0, right height -1(none) → path = 0+0=... height(2)=1
- At node 4 (leaf): height 0, path = 0
- At root: left height 1 (from node 2), right height 0 (from node 4) → path = 1+0 = 1
- Maximum diameter found is 2 (the path 3-2-1-4 has 3 edges; exact value depends on convention used)
Output: Longest path length found while scanning all nodes
Press ▶ Run to watch it step by step.
def diameter(root):
best = 0
def dfs(n):
nonlocal best
if not n:
return 0
l = dfs(n.left)
r = dfs(n.right)
best = max(best, l + r) # path through n
return 1 + max(l, r)
dfs(root)
return best
# example: diameterBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Diameter Time & Space Complexity
When to Use Diameter
- Measuring the 'widest spread' of a hierarchical structure
- Network analysis on tree-shaped topologies
- A classic interview problem combining height calculation with global state tracking
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.