标签:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        else if(p == null) return q;
        else if(q == null) return p;
        else if(p.val < q.val){
            if(root.val > p.val && root.val < q.val) return root;
            else if(root.val == p.val || root.val == q.val) return root;
            else if(root.val < p.val) return lowestCommonAncestor(root.right, p, q);
            else return lowestCommonAncestor(root.left, p, q);
        }
        else{
            if(root.val > q.val && root.val < p.val) return root;
            else if(root.val == p.val || root.val == q.val) return root;
            else if(root.val < q.val) return lowestCommonAncestor(root.right, p, q);
            else return lowestCommonAncestor(root.left, p, q);
        }
    }
}
Jan 12 - Lowest Common Ancestor of a Binary Search Tree; Tree; BST; Recursion;
标签:
原文地址:http://www.cnblogs.com/5683yue/p/5126131.html