您的位置:首页 > 其它

LeetCode------Lowest Common Ancestor of a Binary Search Tree

2016-05-03 10:53 393 查看

题目简介

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),找到最近公共祖先(LCA)的两个给定节点的成就。

根据维基百科的定义:“最近公共祖先是定义两节点v和w之间最低的节点不具有V和W的后裔(我们允许一个节点有自己的后裔)。”

例如,最近的公共祖先(LCA)节点2和8是6。另一个例子是LCA节点2和4是2,因为一个节点可以是自己根据LCA的定义。


自己的解法

public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val == root.val||q.val ==root.val)
return root;
while(true){
TreeNode leftroot =findCurrent(root, p);
TreeNode rightroot =findCurrent(root, q);
if(leftroot != null&&leftroot.val == q.val)
return leftroot;
else if(rightroot !=null&&rightroot.val == p.val)
return rightroot;
else if(leftroot != null&&rightroot != null&&leftroot.val == rightroot.val)
return leftroot;
p = leftroot;
q = rightroot;
}
}
public TreeNode findCurrent(TreeNode root, TreeNode p){
if(p.val == root.val)
return root;
if(root == null)
return root;
else{
TreeNode left = root.left;
TreeNode right = root.right;
if(left != null&&left.val == p.val)
return root;
else if(right !=null&&right.val == p.val)
return root;
else if(p.val <root.val)
return findCurrent(left,p);
else
return findCurrent(right,p);
}
}
}


题目的意思是寻找一棵二叉排序数的两个节点的最近祖先,这个最近祖先可以包含它自己。我的思路是这样的通过findCurrent函数找到任意一个节点的祖先节点,然后再主函数里判断,如果没找到的话,继续寻找祖先节点的祖先节点。我提交一直有问题,原因是这样的,比如这样一棵二叉排序树[5,3,6,2,4,null,null,1],给的节点是1和3,按照我的算法返回的是5而正确的节点是3。我的算法如果要寻找的节点某一棵刚好是另一棵的祖先节点,就无法返回正确答案。一般都会返回根节点。

Hot解法

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


Hot解法的代码还是如此的简介,它的主要思路就是一个规律,这两个节点最近的祖先节点,一个节点要比祖先节点的大,另一个要比祖先节点的小。如果不是,那说明这两个节点在同一侧,那么进行递归。

感受:做编程题目,思考往往比敲代码更重要。如果你有一个很好的思路,那么敲起代码来往往是很快的的。如果你的思路不清晰,那么你肯定会跑一次改一次,运气好最后可以通过。运气不好你是无法改对的,因为你的思路就是有问题的。所有我建议大家开始做题前先要进行足够的思考,不要一上来就急着敲代码,如果你的想法够好,那么敲起来代码肯定是事半功倍的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息