/**************************************************************************
*
* 235. [Lowest Common Ancestor of a Binary Search Tree]
* (https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
*
* Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
*
* Note:
* - All of the nodes' values will be unique.
* - p and q are different and both values will exist in the BST.
*
* 6
* / \
* 2 8
* / \ / \
* 0 4 7 9
* / \
* 3 5
* Input p = 2, q = 8, return 6
* Input p = 2, q = 4, return 2
**************************************************************************/
/// Recursive
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (NULL == root || NULL == p || NULL == q) return NULL;
if (p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if (p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
return root;
}
/// Iterative
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *p, TreeNode *q) {
if (NULL == root || NULL == p || NULL == q) return NULL;
while (root) {
if (p->val < root->val && q->val < root->val)
root = root->left;
else if (p->val > root->val && q->val > root->val)
root = root->right;
else
return root;
}
return root;
}