算法:二叉树的最近公共祖先

问题

  • 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
    百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x
    是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

解决


//1、根据路径判断
class Solution {
    Map<Integer, TreeNode> parent = new HashMap<Integer, TreeNode>();
    Set<Integer> visited = new HashSet<Integer>();

    public void dfs(TreeNode root) {            //只是单纯的递的过程,没有归,将结点以及对应的父节点存到散列表中
        if (root.left != null) {
            parent.put(root.left.val, root);
            dfs(root.left);
        }
        if (root.right != null) {
            parent.put(root.right.val, root);
            dfs(root.right);
        }
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root);
        while (p != null) {
            visited.add(p.val);
            p = parent.get(p.val);          //将p的父结点给p
        }
        while (q != null) {
            if (visited.contains(q.val)) {      //如果set中有相应的映射,那么第一次出现的值对应的结点就是最近祖先结点
                return q;
            }
            q = parent.get(q.val);      //将q的父节点赋予q,
        }
        return null;
    }
}

// 2、递归(极简)
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == root || q == root) {
            return root;
        }

        TreeNode l = lowestCommonAncestor(root.left, p, q);         //在左子树找祖先
        TreeNode r = lowestCommonAncestor(root.right, p, q);        //在右子树找祖先;
    
        return l == null ? r : (r == null ? l : root);
    }
}
posted @   new_monkey  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示