TRT
Sign in
easyCoreLeetCode#return height, record best

Diameter of binary tree

Find the longest path between any two nodes by returning heights and recording the best path through each node.

The Runtime Theory Team1 min read
Taught inTree recursion patternsPro — members onlyMost tree problems are solved by one of three recursive shapes: combine the children's answers on the way up, pass information down from the root, or return one value while updating a global best.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [1, 2, 3, 4, 5]

out3

inroot = [1, 2]

out1

inroot = [1]

out0

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

  1. Write height(node) that returns 0 for None and 1 + max(l, r) otherwise.
  2. Inside it, update a variable outside the recursion with l + r.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save