您的位置:首页 > 其它

235. Lowest Common Ancestor of a Binary Search Tree

2016-04-04 13:51 302 查看
/**
* 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) {
//主要分为几种情况
//1 如果p或者q有一个直接与root相等,则直接返回root即可
//2 如果p q都不等于root,则进行下一步判断,如果都在左子树当中,则堆左子树进行递归
//3 如果都在右子树当中,则对右子树进行递归
//4 如果一个在左子树,一个在右子树当中,则当前root就是结果,直接返回即可。

TreeNode temp=root;

if(root==p||root==q)
{
return temp;
}
else
{
if(isIn(temp.left,p)&&isIn(temp.left,q))
{
return lowestCommonAncestor(temp.left,p,q);
}
else if(isIn(temp.right,p)&&isIn(temp.right,q))
{
return lowestCommonAncestor(temp.right,p,q);
}
else
return temp;
}

}
public boolean isIn(TreeNode root,TreeNode target)
{
boolean res=false;
if(target==root)
return true;
else
{
if(root.left!=null)
res=isIn(root.left,target);
if(root.right!=null&&res==false)
res=isIn(root.right,target);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: