zoukankan      html  css  js  c++  java
  • 二叉树中两个节点的最近公共父节点

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

    情况一: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;  
    }  
     
  • 相关阅读:
    bzoj3007: 拯救小云公主
    bzoj4316: 小C的独立集
    PostgreSQL Replication之第三章 理解即时恢复(3)
    PostgreSQL Replication之第三章 理解即时恢复(2)
    PostgreSQL Replication之第三章 理解即时恢复(1)
    PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(5)
    PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(4)
    PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(3)
    PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(2)
    PostgreSQL Replication之第二章 理解PostgreSQL的事务日志(1)
  • 原文地址:https://www.cnblogs.com/qingmei/p/4120418.html
Copyright © 2011-2022 走看看