Diameter of Binary Tree
Easy
Topics
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 not pass through the root).
Example 1
The shaded path is the longest between any two nodes, and the answer counts its edges — 3 — not its nodes. It need not pass through the root: at each node the best path through it is left height plus right height, so one post-order pass returns a height while recording that maximum.
Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [1,2,3,4,5] Output: 3
Example 2
Input: root = [1,2] Output: 1
Constraints
- 1 <= number of nodes <= 10^4
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
The longest path that bends at a node uses that node’s left height plus its right height (in edges). Compute heights bottom-up and track the best bend anywhere.
Approach
- Write a helper returning the height of a subtree in nodes.
- At each node, the candidate diameter is
leftHeight + rightHeight(edges). - Update a global best; return
1 + max(left, right)upward.
Dry Run
1
/ \
2 3
/ \
4 5
depth() returns a HEIGHT in nodes, while self.best accumulates a path length in
EDGES. Two different units in one function, which is where the off-by-one lives.
node 4 l=0 r=0 bend l+r=0 best 0 -> 0 returns 1
node 5 l=0 r=0 bend l+r=0 best 0 -> 0 returns 1
node 2 l=1 r=1 bend l+r=2 best 0 -> 2 returns 2
node 3 l=0 r=0 bend l+r=0 best 2 -> 2 returns 1
node 1 l=2 r=1 bend l+r=3 best 2 -> 3 returns 3
answer 3 (the path 4 -> 2 -> 1 -> 3, which is 4 nodes and 3 edges)
Every node is asked one question on the way back up: what is the longest path that
BENDS here? That is l + r, with no +1, because l and r already count the edges
down into each child. Node 2 proposes 2 for the path 4 -> 2 -> 5; node 1 proposes
3 and wins.
The answer is kept in self.best rather than returned, and that is the point of the
whole shape. The value a node returns upward (1 + max(l, r)) is a straight-line
height, which is what its parent needs; the bending path cannot be passed up,
because a parent cannot extend a path that already turned. Two different
quantities, one traversal.Complexity
- Time — O(n): one bottom-up pass.
- Space — O(h): recursion stack.
Common Pitfalls
- The diameter counts edges, not nodes — do not add 1 to
l + r.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def diameterOfBinaryTree(self, root):
self.best = 0
def depth(node):
if not node:
return 0
l = depth(node.left)
r = depth(node.right)
self.best = max(self.best, l + r)
return 1 + max(l, r)
depth(root)
return self.bestimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
best = 0;
depth(root);
return best;
}
int best;
int depth(TreeNode node) {
if (node == null) return 0;
int l = depth(node.left), r = depth(node.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int diameterOfBinaryTree(TreeNode* root) {
int best = 0;
function<int(TreeNode*)> depth = [&](TreeNode* node) -> int {
if (!node) return 0;
int l = depth(node->left), r = depth(node->right);
best = max(best, l + r);
return 1 + max(l, r);
};
depth(root);
return best;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var diameterOfBinaryTree = function(root) {
let best = 0;
const depth = node => {
if (!node) return 0;
const l = depth(node.left), r = depth(node.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
};
depth(root);
return best;
};