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

算法-最近公共祖先

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

算法-最近公共祖先

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

236. 二叉树的最近公共祖先
首先,什么是最近公共祖先,这个要搞清楚


class Solution {
    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 root;
        else if(left==null) 
            return right;
        else if(right==null) 
            return left;
        else
            return null; //本颗子树上没有
    }
}
二叉搜索树的最近公共祖先

添加链接描述

很明显利用bst的性质

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null || root==p || root==q){
            return root;`在这里插入代码片`
        }
        if(p.valroot.val && q.val>root.val){
            return lowestCommonAncestor(root.right,p,q);
        }else { //必然是分列左右
            return root;
        }
    }
}
找到二叉树中的距离

添加链接描述
先找到p和q的最近公共祖先f,然后分别计算pq到f的距离

class Solution {
    int disQ,disP;
    public int findDistance(TreeNode root, int p, int q) {
        TreeNode lowestFather=getLowsetF(root,p,q);
        getDis(lowestFather,p,q,0);
        return disP+disQ;
    }

    private void getDis(TreeNode node, int p, int q, int dis) {
        if (node==null){
            return;
        }
        if (node.val==p){
            disP=dis;
        }
        if (node.val==q){
            disQ=dis;
        }
        if (disQ!=0 && disP!=0){
            return;
        }
        getDis(node.left,p,q,dis+1);
        getDis(node.right,p,q,dis+1);
    }

    private TreeNode getLowsetF(TreeNode root, int p, int q) {
        if (root==null){
            return null;
        }
        if (root.val==p || root.val==q){
            return root;
        }
        TreeNode left=getLowsetF(root.left,p,q);
        TreeNode right=getLowsetF(root.right,p,q);
        if (left!=null && right!=null){
            return root;
        }else if (left==null){
            return right;
        }else if (right==null){
            return left;
        }else {
            return null;
        }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/718129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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