My first instinct was to do some kind of path-tracking approach, storing ancestors in a set, which works but completely ignores the BST structure.
Leverage the BST property: starting from the root, if both p and q are less than the current node, move left; if both are greater, move right; otherwise, the current node is the lowest common ancestor. This iterative approach runs in O(h) time and O(1) space, where h is the tree height.
Pro tip: Clarify that this solution exploits the BST ordering, unlike the general binary tree LCA which requires post-order traversal. Mention that the iterative approach avoids recursion stack overhead and is more space-efficient.
Confirm that the tree is a BST, nodes p and q are distinct and guaranteed to exist, and that node values are unique. Discuss edge cases like p or q being the root, or one being an ancestor of the other.
State that for any node, all values in the left subtree are smaller and all values in the right subtree are larger. This ordering allows us to decide the direction to traverse.
Start at the root. While the current node is not null, compare its value with p and q. If both are smaller, go left; if both are larger, go right; otherwise, return the current node as the LCA.
Time complexity is O(h) where h is the height of the tree (O(log n) for balanced BST, O(n) worst-case). Space complexity is O(1) for iterative, O(h) for recursive due to call stack.
Mention that a recursive solution is also possible but uses stack space. Contrast with the general binary tree LCA algorithm which requires post-order traversal and does not assume BST ordering.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.