← Back to DSA Animator
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.