235. Lowest Common Ancestor of a Binary Search Tree

Recursive

  • If p and q are larger than the current node, find the LCA in the right tree
  • If p and q are smaller than the current node, find the LCA in the left tree
  • If they are on both sides of the current node, the current node is their LCA
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right, p, q);
        } else if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left, p, q);
        } else {
            return root;
        }
    }
}