Problem
Section titled “Problem”Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:

Input: root = [1,2,3,4,5]Output: 3Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].Example 2:
Input: root = [1,2]Output: 1Constraints:
- The number of nodes in the tree is in the range .
-
Node.val
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Every path in a tree has a unique highest node: the path climbs up from one end to that node and goes down to the other end. If the highest node is u, the longest such path goes as deep as possible on both sides, so its length is height(u->left) + height(u->right), where height counts the nodes on the longest downward path (0 for an empty subtree), i.e. the edges from u down through that child.
So the diameter is the maximum of height(left) + height(right) over all nodes. A single post-order DFS computes each node’s height from its children’s heights and, at the same time, updates the best sum — every node is processed once, with no repeated height computations.
Algorithm
Section titled “Algorithm”height(node, best)returns0fornullptr.- Otherwise compute
l = height(node->left, best)andr = height(node->right, best). - Update
best = max(best, l + r): the longest path whose highest node isnode. - Return
1 + max(l, r), the height ofnode. diameterOfBinaryTreestartsbestat0, runsheight(root, best)and returnsbest.
Walkthrough
Section titled “Walkthrough”Example 1. Each node shows the height returned to its parent and the candidate l + r; the best candidate is at the root:
The answer is 3 (for example the path 4 → 2 → 1 → 3).
Complexity
Section titled “Complexity”- Time: — each node is visited exactly once and does constant work.
- Space: for the recursion stack, where is the tree height ( for a skewed tree of nodes, which is still a safe recursion depth).
Edge cases
Section titled “Edge cases”- Single node:
l = r = 0, so the diameter is0. - The longest path does not pass through the root (e.g. a deep left subtree with a tiny right one):
bestis updated at every node, not only at the root, so it is still found. - Skewed tree (Example 2): the path ends at the root, and
l + rat the root equals the depth of the chain.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { int height(TreeNode* node, int& best) { if (!node) return 0; int l = height(node->left, best); int r = height(node->right, best); best = max(best, l + r); // longest path whose highest node is `node` return 1 + max(l, r); }
public: int diameterOfBinaryTree(TreeNode* root) { int best = 0; height(root, best); return best; }};class Solution { private int best;
public int diameterOfBinaryTree(TreeNode root) { best = 0; height(root); return best; }
private int height(TreeNode node) { if (node == null) return 0; int l = height(node.left); int r = height(node.right); best = Math.max(best, l + r); // longest path whose highest node is `node` return 1 + Math.max(l, r); }}class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: best = 0 height = {} # heights of finished subtrees whose parent is not finished yet stack = [(root, False)] while stack: # post-order: children's heights before the parent's node, children_done = stack.pop() if node is None: continue if children_done: l = height.pop(node.left, 0) r = height.pop(node.right, 0) best = max(best, l + r) # longest path whose highest node is `node` height[node] = 1 + max(l, r) else: stack.append((node, True)) stack.append((node.left, False)) stack.append((node.right, False)) return bestGive it a try first
Attempt the problem on LeetCode — the code will still be here.
