Diameter of Binary Tree — Coding Interview Walkthrough
The core approach: Diameter of Binary Tree is solved with a post-order DFS in O(n) time and O(h) space. At each node, compute the depth of the left and right subtrees. The diameter through that node is their sum. A global variable tracks the maximum across all nodes, since the longest path may not pass through the root.
Diameter of Binary Tree looks identical to Maximum Depth at a glance, and that’s exactly the trap. The candidates who fail this problem aren’t missing the recursion. They’re computing the diameter through the root only and returning a wrong answer for trees where the longest path is buried in a subtree. Recognizing when the answer lives outside the return value is the real test.
Already know how to solve Diameter Of Binary Tree? Try a Diameter Of Binary Tree mock interview on Intervu →
The Problem
Given the root of a binary tree, return the length of the diameter of the tree. The diameter is the length of the longest path between any two nodes. This path may or may not pass through the root. The length of a path between two nodes is the number of edges between them.
Example 1
Input
1
/ \
2 3
/ \
4 5
Output
3
The longest path is 4 → 2 → 1 → 3 or 5 → 2 → 1 → 3, both with 3 edges.
Example 2
Input
1
/
2
Output
1
What Interviewers Are Actually Testing
| Skill | What Interviewers Observe |
|---|---|
| Non-root path insight | Do you realize the longest path may not go through the root? |
| Separation of concerns | Can you separate what you return versus what you track? |
| DFS with side effects | Do you use a nonlocal/instance variable to track the running max? |
| Depth vs. diameter | Do you correctly frame diameter as left_height + right_height? |
| Clean recursion | Is your code concise and correct without special-casing? |
Step 1: Clarifying Questions
1. Is diameter measured in edges or nodes? Edges. The diameter of a single-node tree is 0, not 1.
2. Can the diameter path pass through non-root nodes? Yes. This is the key point. The longest path might not go through the root at all.
3. What is the diameter of an empty tree? 0. No nodes means no edges.
4. Can the tree be skewed? Yes. In a skewed tree (linked list), the diameter equals n-1 edges.
Step 2: A First (Broken) Idea
def diameterOfBinaryTree_wrong(root):
if root is None:
return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return left + right # Only considers paths through THIS node
This fails because it only considers paths through the root. If the longest path is entirely in the left subtree, this returns the wrong answer.
Step 3: The Key Insight
At every node, the longest path passing through that node is left_height + right_height (in edges). The global diameter is the maximum of this value across all nodes. The trick: you need to track this maximum globally as you recurse, while the function itself returns the height (not the diameter) so the parent can use it.
This separation — return height, track diameter — is the key pattern.
Step 4: Optimal Strategy
- Use a DFS helper that returns the height of each subtree.
- At every node, compute
left_height + right_height— this is the diameter through this node. - Update the running maximum diameter.
- Return
1 + max(left_height, right_height)to the parent (this is the height). - After the DFS, the stored maximum is the answer.
Python Implementation
class Solution:
def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
self.max_diameter = 0
def height(node: Optional[TreeNode]) -> int:
if node is None:
return 0
left_h = height(node.left)
right_h = height(node.right)
# Update global diameter: path through this node
self.max_diameter = max(self.max_diameter, left_h + right_h)
# Return height to parent
return 1 + max(left_h, right_h)
height(root)
return self.max_diameter
Why self.max_diameter? The diameter isn’t always at the root, so we can’t just return it up the stack. We need a side-channel to track the maximum across all nodes.
Time & Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Every node visited exactly once |
| Space | O(h) | Call stack depth equals tree height |
Common Interview Mistakes
-
Only considering paths through the root. This is the most common mistake — returning
maxDepth(left) + maxDepth(right)fromdiameterOfBinaryTreewithout recursing into subtrees. -
Calling
maxDepthseparately inside the loop. Computing height separately for each node makes the solution O(n²). Computing height and diameter together in one DFS is O(n). -
Confusing edges and nodes. The problem asks for edges. A leaf has diameter 0, not 1. A two-node tree has diameter 1.
-
Forgetting the
max_diameter = 0initialization. For a single-node tree, the diameter is 0. Initializing to -1 or 1 would give wrong results. -
Returning the diameter instead of height from the helper. The helper must return height so the parent can use it — the diameter is tracked separately.
What a Strong Candidate Sounds Like
“The key insight is that the longest path might not go through the root. At every node, the longest path through that node is left_height + right_height in edges. I need to track the maximum of this value globally as I do a DFS. The DFS itself returns the height of each subtree — that’s what the parent needs — while the diameter is tracked as a side effect. This gives O(n) time in a single pass.”
Example Interview Dialogue
Interviewer: Why can’t you just return the diameter from your recursive function?
Candidate: Because the function needs to return height to its parent — that’s what enables the parent to compute its own diameter. The diameter at any node is left_height + right_height, but the parent needs the height, not the diameter. These are different values, so I use a separate variable to carry the running diameter maximum.
Interviewer: What’s the diameter of a linked-list-shaped tree of n nodes?
Candidate: n-1 edges. The longest path goes from one end to the other, which is n-1 edges. The DFS would see left_height = n-1 and right_height = 0 at the root, giving diameter = n-1.
Related Problems to Practice
- Maximum Depth of Binary Tree — Foundation. Understand height before diameter.
- Binary Tree Maximum Path Sum — Same pattern but with values instead of edges. A harder version of this exact problem.
- Balanced Binary Tree — Also uses height computation with a separate tracking variable.
Frequently Asked Questions
Does the longest path (diameter) of a binary tree always pass through the root?
No, the longest structural path can exist entirely within a single deeper subtree without passing through the primary root node. Finding the correct diameter requires recalculating and comparing the maximal left and right height sum globally across every node in the graph structure.
What is the time complexity of the optimal solution for measuring the Diameter calculation?
Rather than computing height repetitively, an optimal Bottom-Up DFS retrieves the max depths in a single pass while tracking the largest diameter sum sequentially. This condenses the execution exclusively to a true O(N) time complexity.
Practice This in a Mock Interview
Diameter of Binary Tree has one gotcha that trips up most candidates on their first attempt — the “path doesn’t go through root” case. The only way to make that insight feel automatic is to practice articulating it out loud before you code, not after you’ve already written the wrong solution.
Start a mock interview for Diameter of Binary Tree on Intervu.
Further reading:
- How to Prepare for a Coding Interview in 2026, the complete roadmap
- Why LeetCode alone isn’t enough, and what to practice instead
- Practice any LeetCode problem as a live mock interview
- The Grind 75 Pathway, a structured study plan with AI practice links
- Browse all walkthroughs on GitHub, condensed solutions with code