LeetCode – Lowest Common Ancestor of a Binary Search Tree (Java)

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

Analysis

This problem can be solved by using BST property, i.e., left < parent < right for each node. There are 3 cases to handle.

Java Solution 1 – Recursive

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    TreeNode m = root;
 
    if(m.val > p.val && m.val < q.val){
        return m;  
    }else if(m.val>p.val && m.val > q.val){
        return lowestCommonAncestor(root.left, p, q);
    }else if(m.val<p.val && m.val < q.val){
        return lowestCommonAncestor(root.right, p, q);
    }
 
    return root;
}

Java Solution 2 – Iterative

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    TreeNode t = root;
 
    while(t!=null){
        if(p.val >t.val && q.val >t.val){
            t = t.right;
        }else if (p.val<t.val && q.val<t.val){
            t = t.left;
        }else{
            return t;
        }
    }
 
    return null;
}

5 thoughts on “LeetCode – Lowest Common Ancestor of a Binary Search Tree (Java)”

  1. This solution assumes p will always be the smaller node and q the greater, it might not work if p and q were swapped.

  2. Non-recursive solution:

    TreeNode lowestCommonAncestor(TreeNode bst, int v1, int v2) {
    if (bst == null) return null;
    int small = Math.min(v1, v2);
    int great = Math.max(v1, v2);

    TreeNode n = bst;
    while (n != null && (n.value > great || n.value great) {
    n = n.left;
    } else {
    n = n.right;
    }
    }
    return n;
    }

  3. can be shorted as
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if(root.val>p.val && root.val > q.val){
    return lowestCommonAncestor(root.left, p, q);
    }else if(root.val<p.val && root.val root.val && root.val < q.val)
    return root;
    }

  4. Node* FindLCA_BST(Node* root, Node* node1, Node* node2) {
    if (root == nullptr) {
    return nullptr;
    }

    if (root->data data && root->data data) {
    return FindLCA_BST(root->right, node1, node2);
    } else if (root->data > node1->data && root->data > node2->data) {
    return FindLCA_BST(root->left, node1, node2);
    }
    return root;
    }

Leave a Comment