栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

二叉树的最近公共祖先合集

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的最近公共祖先合集

剑指offer86:在二叉树中查找

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        if(root==null||root==p||root==q) return root;
        TreeNode left=lowestCommonAncestor(root.left,p,q);
        TreeNode right=lowestCommonAncestor(root.right,p,q);
        if(left==null&&right==null) return null;
        if(left==null) return right;
        if(right==null) return left;
        return root;
    }

思路:可以理解成是利用后序遍历查找二叉树中的p和q,找到就返回结点,没有找到就返回null。

剑指offer68:

方法一:利用二叉搜索树的特性,左子树<根结点<右子树,比较根结点和pq两点大小,确定两点位置。

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
        while((root.val-p.val)*(root.val-q.val)>0) {
            root=root.val 

方法二:同上题

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/717035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号