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和q都比根节点小,则继续在左子树上查找;若p和q都比根节点大,则在右子树上继续查找。若一个比根节点小,一个比根节点大,则找到了LCA祖先。
/**@author
* 找两个二分查找树的最低公共祖先。
* 对二分查找树来说,最重要的性质就是左子树节点的值都比root节点的值小,右子树上节点的值都比root节点的值大。
* 所以首先第一步就是判断给定的root节点和两个节点是否有空节点,若有空节点,则直接返回null。
* 否则,利用递归的思想去做这道题目。
* 如果两个节点的值中最大的值比root的节点的值小(说明两个节点的值都比root小),则p和q节点的公共祖先在root的左子树上,递归在root的左子树上找最低公共祖先。
* 如果两个节点的值中最小的值比root的节点的值大(说明两个节点的值都比root大),则p和q节点的公共祖先在root的右子树上,递归在root的右子树上找最低公共祖先。
* 如果两个节点的值一个比root节点的值大,一个比root节点的值小,则找到了p和q的最低公共祖先。
* @param root
* @param p
* @param q
* @return
*/
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || p==null || q==null) return null; /*若参数中三个节点有一个为空,则直接返回null*/
if(Math.max(p.val, q.val) < root.val) {
return lowestCommonAncestor(root.left, p, q);
} else if(Math.min(p.val, q.val) > root.val) {
return lowestCommonAncestor(root.right, p, q);
} else return root;
}