intermediate11 min read·Updated September 29, 2026
Binary Tree Diameter Explained: Tracing Path 5-3-2-4-7
Master binary tree diameter with a step-by-step walkthrough of a skewed-root tree where the longest path bypasses the root. Learn the mental model.
By Learnisim AI·Published September 29, 2026
LEARNING ARCSetup → Model in the example → Full trace → Twist → Edge cases → Apply
PREREQUISITES
- Binary tree structure and traversal
- Basic recursion and stack frames
- Tree height calculation via DFS
Why
Why the longest path doesn't always go through the root
Phase 1: The Root-Path Illusion
Imagine you are building a routing system in a network topology shaped like a binary tree. You are given a specific layout: Root node 1 has only a left child 2 and no right child. Node 2 splits into left child 3 and right child 4. Node 3 branches down to 5 and 6, while node 4 has a single left child 7.
If you naively assume that the longest communication path in this network must pass through the top-level server (Root 1), you will measure the path from node 1 down through 2, 3, and 5. That gives you a path length of 3 edges. But a quick trace reveals a longer route: the path starting at leaf 5, going up through 3, crossing at node 2, descending to 4, and ending at leaf 7. This path () completely bypasses root node 1 and spans 4 edges!
This exact failure mode is why a simple "height of left subtree plus height of right subtree from the root" formula fails. The diameter of a binary tree is the longest path between any two nodes in the tree, and that path may live entirely tucked away inside a left or right subtree, miles away from the official root.
1 (Root)
|
2
/ \
3 4
/ \ /
5 6 7
|
2
/ \
3 4
/ \ /
5 6 7
Longest path: 5-3-2-4-7 (4 edges, misses 1)
To capture this correctly, we need a way to inspect every single node in the tree, compute the local paths passing through each node, and track the global maximum without getting trapped by our root-centric assumptions.
Model
The Subtree Height-Accumulation Model
Phase 2: The Subtree Height-Accumulation Model
When we look at our locked working example where root 1 only has a left child 2, we realize that the longest path 5-3-2-4-7 never touches root 1. How can a recursive tree traversal find a path that sits entirely inside a subtree?
The answer is to decouple the local path peak from the node height returned to the parent. As our DFS descends into the tree, every single node acts as a potential turning point for a longest path. Think of each node as a highway interchange: it receives maximum incoming distances from its left and right ramps, adds them together to inspect the local peak diameter passing through it, and then passes only the single tallest outgoing ramp up to its own parent.
In our locked working example, node 2 has a left child 3 (leading to leaf 5) and a right child 4 (leading to leaf 7). When post-order DFS reaches node 2, it evaluates:
•Left height from node 3: 2 edges (path 5-3-2)
•Right height from node 4: 2 edges (path 7-4-2)
- Local peak diameter at node 2: edges
Meanwhile, node 2 reports its height upward as to its parent, root 1. Root 1 computes its own local peak (0 right height plus 3 left height equals 3), but our global maximum tracker safely ignores it because node 2's local peak of 4 was already locked in.
Syntax
Syntax and Recursive Function Signatures for Tree Diameter
Phase 3: Syntax & APIs
To implement our Subtree Height-Accumulation Model on the locked example where node 1 has only a left child 2, we need a clean recursive function signature. In Python, we typically pair a helper function that returns an integer height with a class-level variable tracking the maximum diameter found so far.
Let us look at the surface syntax required to traverse the tree, compute local left and right heights, and update our running maximum. If we forget to track the global state correctly or mix up returning height versus updating diameter, our code will fail on subtrees like the one rooted at node 2.
A common syntax trap is attempting to return both the height and the diameter in a single recursive return value without a class attribute or nonlocal keyword in Python. For instance, writing
return height, max_diam without storing the global state across recursive frames leads to scope confusion or overwritten values during backtracking.Worked example
Tracing the Height Accumulator on a Skewed-Root Tree
Phase 4: Worked example
To see why the global diameter variable is necessary, let's trace our locked example tree: Root
1 has only a left child 2 (no right). Node 2 has left 3 and right 4. Node 3 has left 5 and right 6. Node 4 has left 7. We want to trace how post-order DFS updates the global maxDiameter variable and what heights are returned at each step.Let's trace the execution state using a recursive function that returns height and updates
maxDiameter:Given
•Tree structure:
- Node
1 (left: 2, right: None)- Node
2 (left: 3, right: 4)- Node
3 (left: 5, right: 6)- Node
4 (left: 7, right: None)- Leaf nodes
5, 6, and 7 have no children.- Initial global state:
self.ans = 0Steps
1. Post-order traversal reaches leaf nodes5, 6, and 7:-
height(5) returns 0. left_h = 0, right_h = 0. self.ans = max(0, 0 + 0) = 0. Returns 1 + 0 = 1 to node 3.-
height(6) returns 0. Returns 1 + 0 = 1 to node 3.-
height(7) returns 0. Returns 1 + 0 = 1 to node 4.2. Traversal visits node
-
-
-
- Returns
3:-
left_h from node 5 is 1.-
right_h from node 6 is 1.-
self.ans = max(0, 1 + 1) = 2.- Returns
1 + max(1, 1) = 2 to node 2.3. Traversal visits node
-
-
-
- Returns
4:-
left_h from node 7 is 1.-
right_h from None is 0.-
self.ans = max(2, 1 + 0) = 2.- Returns
1 + max(1, 0) = 2 to node 2.4. Traversal visits node
-
-
-
- Returns
2:-
left_h from node 3 is 2.-
right_h from node 4 is 2.-
self.ans = max(2, 2 + 2) = 4.- Returns
1 + max(2, 2) = 3 to root 1.5. Traversal visits root
-
-
-
- Returns
1:-
left_h from node 2 is 3.-
right_h from None is 0.-
self.ans = max(4, 3 + 0) = 4.- Returns
1 + max(3, 0) = 4.Result
The function finishes and returnsself.ans = 4, representing the path 5-3-2-4-7 containing 4 edges.Practice
Practice Finding the Maximum Path in a Subtree
Phase 5:
Now it is your turn to apply the recursive height-tracking pattern to a small structural variation of our locked tree. Recall our main rule: the global diameter is updated at every node as , even when that node sits deep inside a child branch rather than at the top.
Consider a tree where node
1 has a left child 2 (height 2) and a new right child 8 (height 1). Node 2 still has children 3 and 4 as before, giving it a subtree height of 2. Node 8 is a leaf with height 0. Write out or trace how the global diameter updates as the recursive DFS visits node 2 versus node 1, and identify where the maximum edge count is captured.Apply
Applying the Bottom-Up Height Paradigm to Binary Tree Diameter
Phase 6: Applying the Paradigm Beyond the Root
We have successfully traced our working example where the longest path of 4 edges () bypasses the root node entirely. By decoupling the global diameter tracker from the recursive height return value, we allowed every single node in the tree to act as a potential bridge for the longest path.
To solidify this pattern, consider how this exact same bottom-up accumulation logic handles variations in tree shape. If we encounter a scenario where the tree bifurcates deep down at a leaf-heavy subtree while the other side of the root is a sparse single-child chain, the global variable ensures we never lose track of that deep peak.
Whenever you encounter problems requiring distance between arbitrary nodes in a tree, ask yourself: Can I compute this purely from the child heights at each local pivot, or do I need to pass state downward? For binary tree diameter, the answer is always bottom-up combination.
FAQ
Why doesn't the binary tree diameter always pass through the root?
The diameter is the length of the longest path between any two nodes. If a root node has an absent right child or a lopsided subtree, the longest path can be entirely contained within one of its subtrees, completely bypassing the root.
In the working example with root 1, why is the diameter 4 instead of passing through 1?
At node 2, the left subtree (via
3.has height 2 and the right subtree (via
4.has height 2, yielding a path length of 4 (5-3-2-4-7). Root 1 only has a left child, so any path through root 1 is constrained by its missing right subtree.
What is the time and space complexity of finding the binary tree diameter?
The time complexity is O(N) because every node is visited once during the post-order DFS traversal. The space complexity is O(H), where H is the height of the tree, representing the maximum call stack depth.
How do you calculate height and update diameter simultaneously?
As the recursive DFS returns the height of each subtree (1 + max(left, right)), you simultaneously compute leftHeight + rightHeight at every node to check if it exceeds the global maximum diameter.