// Recursive approach
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p, q); // both p and q are smaller than root, LCA must in the left child tree
else if (root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p, q); // both p and q are larger than root, LCA must in the right child tree
else
return root; // root is in the middle of p and q, so root is the LCA
}
}
// iterative approach
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
if (root.val > p.val && root.val > q.val)
root = root.left; // search the left child tree
else if (root.val < p.val && root.val < q.val)
root = root.right; // search the right child tree
else
break;
}
return root;
}
}