Given the root of a binary tree, return the length, in edges, of the longest path between any two nodes. The path may or may not pass through the root.
Before you code
The longest path turns at some node, going down into both of its subtrees. Its length there is the sum of the two subtrees' heights. Every node is a candidate.
Hints
- Write
height(node)that returns 0 for None and1 + max(l, r)otherwise. - Inside it, update a variable outside the recursion with
l + r. - Return that variable after one traversal: O(n).
Production & complexity notes
When solving Diameter of binary tree on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tree recursion patterns to reinforce the underlying pattern.
What it practices
Returning one value while recording another, from Tree recursion patterns.