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

问题

  • 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
    百度百科中最近公共祖先的定义为:“对于有根树 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 @ 2022-08-09 22:52  new_monkey  阅读(25)  评论(0)    收藏  举报