您的位置:首页 > 其它

LeetCode-Lowest Common Ancestor of a Binary Search Tree

2015-10-20 20:14 369 查看
Problem:

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



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.

Analysis:

这个是二叉搜索树的题,根据二叉搜索树的特点可知:

root.val<root.right.val  且 root.left.val<root.val


那么我们只要判断p和q是否在root的左右分支或者p和q中的一个是root即可。

但是p和q哪个大并不清楚,这里有个绝招

(root.val-p.val)*(root.val-q.val)<=0


Anwser1: 利用死循环查找

/**
* 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) {
while(root!=null){
if((root.val-p.val)*(root.val-q.val)<=0) return root;
else if(root.val>p.val) root=root.left;
else root=root.right;
}
return null;
}
}


Anwser2: 利用递归查找

/**
* 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.val-p.val)*(root.val-q.val)<=0) return root;
else if(root.val>p.val) return lowestCommonAncestor(root.left,p,q);
else return lowestCommonAncestor(root.right,p,q);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: