最小公共祖先LCA

问题描述

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).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

 

解决思路

递归,可以用BST特有的二分递归,也可以普通递归。

 

程序

普通:

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return root;
        }
        if (p == null) {
            return q;
        }
        if (q == null) {
            return p;
        }
        if (p == q) {
            return p;
        }
        return helper(root, p, q);
    }
    
    private static TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        
        TreeNode left = helper(root.left, p, q);
        TreeNode right = helper(root.right, p, q);
        
        if (left != null && right != null) {
            return root;
        }
        return left == null ? right : left;
    }
}

 

BST特性:

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return root;
        }
        if (p == null) {
            return q;
        }
        if (q == null) {
            return p;
        }
        if (p == q) {
            return p;
        }
        return helper(root, p, q);
    }
    
    private static TreeNode helper(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > root.val && q.val > root.val) {
            return helper(root.right, p, q);
        }
        if (p.val < root.val && q.val < root.val) {
            return helper(root.left, p, q);
        }
        return root;
    }
}

  

posted @ 2015-07-12 20:40  Chapter  阅读(212)  评论(0编辑  收藏  举报