Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Diameter of Binary Tree
Problem
Given the root of a binary tree, return the length of the longest path between any two nodes in the tree. Path length is measured in edges, and the path is not required to pass through the root.
- The tree has between 1 and 30,000 nodes.
- Node values are integers and do not affect the answer.
Examples
root = [6, 3, 9, 1, 4, None, 12, None, None, 2]→5. The path2 → 4 → 3 → 6 → 9 → 12has five edges and happens to pass through the root.root = [10, 20]→1. Two nodes, one edge.root = [5]→0. A single node has no edges.
Hints
- Every path has a unique highest node, the point where it stops going up and starts going down. Think about the path from that node's point of view.
- At that highest node, how far can the path descend into the left subtree, and how far into the right?
- Post-order DFS that returns each subtree's height and, as a side effect, updates a running maximum of
height(left) + height(right).
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.