Question presented to candidate: "Given the root of a binary tree, write a Python function that returns the length of its diameter: the number of edges on the longest path between any two nodes. The path does not have to pass through the root."
What a strong answer should cover:
- Every path has a highest (bend) node; the longest path bending at a node has height(left) + height(right) edges.
- The answer is the maximum over all nodes, so a root-only computation is wrong when the longest path sits inside one subtree.
- One post-order pass: return the height to the parent, record the best left + right on the side โ O(n) time, O(h) space.
- Why recomputing heights at every node is O(n ยท h), O(nยฒ) on a chain.
- Python details: a nested helper with
nonlocal best(or a one-element list) instead of a global, and the 1000-frame recursion limit for deep chains. - Edges vs nodes: a single node has diameter 0.
Clarifying questions expected:
- Is the length measured in edges or in nodes?
- Must the path go through the root?
Code / implementation expected: Yes โ a nested height(node) helper inside diameter(root), in Python 3.