二叉树中两个节点的最近公共父节点

这是京东周六的笔试题目   当时不在状态,现在想来肯定是笔试就被刷掉了,权当做个纪念吧。  这个问题可以分为三种情况来考虑:

情况一:root未知,但是每个节点都有parent指针
此时可以分别从两个节点开始,沿着parent指针走向根节点,得到两个链表,然后求两个链表的第一个公共节点,这个方法很简单,不需要详细解释的。

情况二:节点只有左、右指针,没有parent指针,root已知
思路:有两种情况,一是要找的这两个节点(a, b),在要遍历的节点(root)的两侧,那么这个节点就是这两个节点的最近公共父节点;
二是两个节点在同一侧,则 root.getLeft() 或者 root.getRight() 为 NULL,另一边返回a或者b。那么另一边返回的就是他们的最小公共父节点。
递归有两个出口,一是没有找到a或者b,则返回NULL;二是只要碰到a或者b,就立刻返回。
代码如下:

//二叉树结点描述
class NodeTree{
private String data;
private NodeTree left;
private NodeTree right;
//Get  AND  Set 
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public NodeTree getLeft() {
return left;
}
public void setLeft(NodeTree left) {
this.left = left;
}
public NodeTree getRight() {
return right;
}
public void setRight(NodeTree right) {
this.right = right;
}
//全参数构造函数
public NodeTree(String data, NodeTree left, NodeTree right) {
super();
this.data = data;
this.left = left;
this.right = right;
}
//空参数构造函数
public NodeTree() {
super();
}
}
//节点只有左指针、右指针,没有parent指针,root已知  
public NodeTree findLowestCommonAncestor(NodeTree root , NodeTree a , NodeTree b)  
{  
    if(root == null)  
        return null;  
    if(root == a || root == b)  
        return root;  
    NodeTree left = findLowestCommonAncestor(root.getLeft() , a , b);  
    NodeTree right = findLowestCommonAncestor(root.getRight(), a , b);  
    if(left!=null && right!=null)  
        return root;  
    return left!=null ? left : right;  
}   

情况三: 二叉树是个二叉查找树,且已知root和两个节点的值(a, b)      // 二叉树是个二叉查找树,且root和两个节点的值(a, b)已知  

NodeTree findLowestCommonAncestor(NodeTree root , NodeTree a , NodeTree b)  
{  
    int min = 0;int max = 0;  
    if(a.getData() < b.getData()){
      min = a.getData(); max = b.getData(); 
    }else  
        min = b.getData(); max = a.getData();  
    while(root!=null)  
    {  
        if(root.getData() >= min && root.getData() <= max)  
            return root;  
        else if(root.getData() < min && root.getData() < max)  
            root = root.getRight();  
        else  
            root = root.getLeft();  
    }  
    return null;  
}  
 

转载于:https://www.cnblogs.com/qingmei/p/4120418.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值