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.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

public class Solution {
    
    TreeNode lca = null; 
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        f (root, p, q); 
        return lca; 
    }
    
    /**
     * p in it --> 1
     * q int it --> 2
     * both in it --> 3
     **/
    public int f(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) 
            return 0; 
        int l = f(root.left, p, q);
        int r = f(root.right, p, q); 
        
        if (root != p && root != q) {
            if (l == 1 && r == 2) {
                lca = root; 
                return 3; 
            } 
            if (l == 2 && r == 1) {
                lca = root; 
                return 3; 
            }
            
            return l+r;
        } else if (root == p) {
            if (l == 2 || r == 2) {
                lca = root; 
                return 3; 
            }
            return 1; 
        } else if (root == q) {
            if (l == 1 || r == 1) {
                lca = root; 
                return 3;
            } 
            return 2; 
        } else {
            return 0; 
        }
    }
}

Solution 2:

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
		if (root == null || p == null || q == null)
			return null;
		if (Math.max(p.val, q.val) < root.val)
			return lowestCommonAncestor(root.left, p, q);
		if (Math.min(p.val, q.val) > root.val)
			return lowestCommonAncestor(root.right, p, q);
		return root;    
        
    }
}
Advertisements

One Comment Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s