Diameter of Binary Tree
On this page
Problem statement
Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes. The path may or may not pass through the root. An empty tree or a single node has diameter 0.
A short tree problem that checks one idea: a function can return one value to its parent (the height) while updating a different answer on the side (the best path). The same pattern solves Binary Tree Maximum Path Sum and several other "longest path in a tree" questions. Original problem: LeetCode 543.
Example

Input: root = [1, 2, 3, 4, 5, null, null, 7, null, null, 8, 9, null, null, 10]
Output: 6 # 9 - 7 - 4 - 2 - 5 - 8 - 10
Input: root = [1, 2, 3]
Output: 2 # 2 - 1 - 3
Constraints (assumed)
- 0 ≤ number of nodes ≤ 10⁴.
- The tree may be very unbalanced (depth up to 10⁴).
What this question tests
- Seeing that every path has one highest node where it bends, so you can check every node as the bend.
- A post-order DFS that returns one thing (height) and records another (best L + R).
- Being exact about edges vs nodes.
Questions to ask first
- Length in edges or in nodes? (Here: edges; the node count is one more.)
- Does the path have to go through the root? (Here: no.)
- What should an empty tree return? (Here: 0.)
- How deep can the tree be? Deep trees can overflow the call stack in recursive code.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.