【99.二叉树的最近公共祖先】

46 阅读1分钟

题目

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

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

 

示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3

题解

方式一:哈希表

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    // key:child  value:father
    Map<TreeNode, TreeNode> father = new HashMap<>();
    order(root, father);
    
    // 先记录p的所有祖先
    Set<TreeNode> set = new HashSet<>();
    while (father.containsKey(p)) {
        // p也可以是自己的祖先
        set.add(p);
        p = father.get(p);
    }
    
    // 遍历q的所有祖先
    while (father.containsKey(q)) {
        if (set.contains(q)) {
            return q;
        }
        q = father.get(q);
    }
    
    return root;
}

public void order(TreeNode node, Map<TreeNode, TreeNode> father) {
    if (node == null) {
        return;
    }
    if (node.left != null) {
        father.put(node.left, node);
    }
    if (node.right != null) {
        father.put(node.right, node);
    }
    order(node.left, father);
    order(node.right, father);
}

方式二:递归

TreeNode result = null;
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    dfs(root, p, q);
    return result;
}

public boolean dfs(TreeNode node, TreeNode p, TreeNode q) {
    if (node == null) return false;
    boolean left = dfs(node.left, p, q);
    boolean right = dfs(node.right, p, q);
    if ((left && right) || ((node.val == p.val || node.val == q.val) && (left || right))) result = node;
    return left || right || (node.val == p.val || node.val == q.val);
}

总结

算法:递归哈希表