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

        _______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.

这个题说的是二叉搜索树,找下规律。

如果p.val和q.val一个比root.val大,一个比root.val小,或者有一个等于根节点的val,那么根节点就是他们的最小共同父节点。

如果p.val和q,val都比root.val大,那么他们的最小共同父节点肯定在根节点的右侧。

如果p.val和q,val都比root.val小,那么他们的最小共同父节点肯定在根节点的左侧。

代码如下:

public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int num=(p.val-root.val)*(q.val-root.val);
        if(num<=0)
        	return root;
        if(p.val-root.val>0)
        	return lowestCommonAncestor(root.right, p, q);
        return lowestCommonAncestor(root.left, p, q);
    }
}


你可能感兴趣的:(java,LeetCode,递归,tree)