Question presented to candidate: "Given the root of a binary tree โ not necessarily a binary search tree โ and two nodes p and q that are in the tree, write a Python function that returns their lowest common ancestor: the deepest node that has both p and q as descendants, where a node counts as a descendant of itself."
What a strong answer should cover:
- The definition, including that p can be the answer when it is an ancestor of q.
- The recursive post-order search: return the node if it is null, p or q; if both children return non-null, the current node is the LCA.
- O(n) time and O(h) space, and why the early return is safe only when both nodes exist.
- How to handle a possibly missing node (count matches, no early return) and the parent-map alternative.
- Python details: compare nodes with
is(identity), nodes hash by identity so they work as dict keys, and the 1000-frame recursion limit on deep trees. - The BST shortcut and why it does not apply to a general binary tree.
Clarifying questions expected:
- Is it a BST or a general binary tree?
- Are both nodes guaranteed to be in the tree, and are they given as nodes or as values?
Code / implementation expected: Yes โ lca(root, p, q) returning a node, in Python 3.