DSA AnimatorDSA animations
Diameter of Binary Tree LC #543 Easy DFS Post-order · Global Max
Problem

Given the root of a binary tree, return the length of the diameter — the longest path between any two nodes (measured in edges). The path may or may not pass through the root.

Example 1
Input: root = [1,2,3,4,5]
Output: 3
Explanation: Path 4→2→1→3 or 5→2→1→3, length = 3 edges.
Example 2
Input: root = [1,2]
Output: 1
Constraints: 1 ≤ nodes ≤ 10⁴  |  −100 ≤ Node.val ≤ 100
Try Examples
Custom:
Approach
DFS Post-order: diameter = max(L + R) across all nodes
At each node the longest path through it = leftHeight + rightHeight. Post-order DFS computes heights bottom-up, updating a global diameter at every node.
Binary Tree
Diameter Tracker
Global Diameter
0
edges
Left Height (L)
—
Right Height (R)
—
Select a step to see the L+R calculation…
Post-order Return Values
NodeL.HR.Hheightdiam@
Processing…
Recursion Stack
Variables
Current Node
—
Left H
—
Right H
—
Diameter
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Base: node == null → return 0
2
Post-order recurse left: L = depth(node.left)
3
Post-order recurse right: R = depth(node.right)
4
Update global: diameter = max(diameter, L + R)
5
Return height: 1 + max(L, R) to parent
Time
O(n)
Space
O(h)
Why Post-order + Global Max?

The diameter path may not pass through the root. By maintaining a global variable updated at every node, we capture the widest path anywhere in the tree. Post-order guarantees both L and R heights are known before computing L+R — children inform parents, not the reverse.

How to solve Diameter of Binary Tree

LeetCode 543 · Easy · Tree · Pattern: DFS Height

Why the obvious approach is slow

For every node, you could compute the heights of its two subtrees separately. Recomputing heights again and again makes that O(n²). We can get every height and every candidate in a single pass.

The key idea

Write a function that returns the height of a node, counted in nodes. For a node, ask for the left height and the right height. The longest path that bends at this node uses left plus right edges. Update a global best with left plus right. Then return 1 plus the larger of the two heights to the parent.

Remember

Return height, but record the diameter on the side. Left height plus right height is the path that bends at this node.

Run the animation above on your own input, or watch the 1:58 video explanation of Diameter of Binary Tree with a dry run and Java code.

More Tree problems