I knew the recursive approach but fumbled explaining why it works.
Clarify the problem constraints (e.g., binary tree vs. BST, nodes guaranteed to exist) and then present a recursive post-order traversal solution that returns the LCA. Explain that if the current node is p or q, it is the LCA; otherwise, recurse on left and right subtrees and combine results.
Pro tip: Mention that the recursive solution runs in O(n) time and O(h) space, and that you can optimize space to O(1) with a parent-pointer approach if the tree nodes have parent links. Also, note that if the tree is a BST, you can solve it iteratively in O(h) time by comparing values.
Ask whether the tree is binary (not necessarily BST), whether p and q are guaranteed to be in the tree, and whether a node can be its own descendant (yes, per problem).
Decide between recursive post-order traversal (general binary tree) or iterative BST-specific approach. For Amazon, the recursive solution is expected.
Define a function that returns the LCA. Base case: if root is null or root equals p or q, return root. Recurse left and right; if both return non-null, root is LCA; otherwise return the non-null child.
State time complexity O(n) and space O(h) due to recursion stack. Walk through an example to verify correctness, including cases where one node is ancestor of the other.
Mention iterative solution with parent pointers (O(1) space) or BST-specific O(h) solution. Also note handling of nodes not present (if not guaranteed).
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.