zoukankan      html  css  js  c++  java
  • 【Offer】[68] 【树中两个结点的最低公共祖先】

    题目描述

      输入两个树结点,求它们的最低公共祖先。

    [牛客网刷题地址]无

    思路分析

      该题首先要确定是否为二叉树,还要确定是否为二叉搜索树,是否有父指针,或者仅仅是普通二叉树。

    1. 树为二叉搜索树时,最低公共祖先结点的大小在两个树结点大小的中间。
    2. 树为普通树时,使用遍历将子结点的信息往上传递。在左右子树中进行查找是否存在两个树结点,如果两个树结点分别在左右子树上,说明该根结点就是它们的最低公共祖先。

    测试用例

    1. 功能测试:普通树,左斜树,右斜树
    2. 特殊测试:null

    Java代码

    public class Offer068 {
        public static void main(String[] args) {
            test1();
            test2();
            test3();
            
        }
    
        /*
         * 二叉搜索树
         * 利用大小关系即可
         */
        public TreeNode getLowestCommonParentBST(TreeNode root,TreeNode node1,TreeNode node2) {
            while(true) {
                if(root==null)
                    return root;
                if(root.val<node1.val && root.val<node2.val)
                    root=root.right;
                else if(root.val>node1.val && root.val>node2.val)
                    root=root.left;
                else
                    return root;
            }
        }
         
         
        /*
         * 普通二叉树
         * 将下面结点的信息利用递归s往上传递
         */
        public TreeNode getLowestCommonParent(TreeNode root,TreeNode node1,TreeNode node2) {
            if(root==null || root== node1 || root== node2)
                return root;
            TreeNode left=getLowestCommonParent(root.left, node1, node2);
            TreeNode right=getLowestCommonParent(root.right, node1, node2);
            return left==null? right:right==null? left:root;
        //  上面这句代码就是:
        //  if(left==null) {
    //            return right;
        //  }else {
    //        if(right==null)
    //            return left;
    //        else
    //            return root;
        //  }
        }
    
    
        private static void test1() {
    
        }
    
        private static void test2() {
    
        }
        private static void test3() {
    
        }
    
    }
    

    代码链接

    剑指Offer代码-Java

  • 相关阅读:
    Angular
    linux mysql 5.7.25 安裝
    J2CACHE 两级缓存框架
    MYSQL 事务测试
    安装配置ftp服务器
    使用docker 安装 GITLIB
    Elastic serarch 安装
    centos firewalld 基本操作【转】
    KAFKA 监控管理界面 KAFKA EAGLE 安装
    redis 的一主二从三哨兵模式
  • 原文地址:https://www.cnblogs.com/haoworld/p/offer68-shu-zhong-liang-ge-jie-dian-de-zui-di-gong.html
Copyright © 2011-2022 走看看