【Lintcode】88. Lowest Common Ancestor of a Binary Tree

题目地址:

https://www.lintcode.com/problem/lowest-common-ancestor-of-a-binary-tree/description

给定一棵二叉树和树中的两个节点,求最近公共祖先。

可以用递归的方式求解。代码如下(证明附在后面):

public class Solution {
    /*
     * @param root: The root of the binary search tree.
     * @param A: A TreeNode in a Binary.
     * @param B: A TreeNode in a Binary.
     * @return: Return the least common ancestor(LCA) of the two nodes.
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
        // write your code here
        if (root == null) {
            return null;
        }
        
        if (root == A || root == B) {
            return root;
        }
        
        TreeNode left = lowestCommonAncestor(root.left, A, B);
        TreeNode right = lowestCommonAncestor(root.right, A, B);
        
        if (left == null) {
            return right;
        } else if (right == null) {
            return left;
        } else {
            return root;
        }
    }
}

class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) {
        this.val = val;
    }
}

时间复杂度 O ( n ) O(n) ,空间 O ( h ) O(h)

算法正确性证明:
函数的含义是在root为根的二叉树中寻找 A A B B 的最近公共祖先(如果 A A B B 都存在的话),否则,如果只存在 A A B B 的话,就返回 A A 或者 B B ,都不存在则返回null。

数学归纳法。如果树只有 0 0 1 1 个节点时,结论正确。假设对 k k 个节点时也对,当树有 k + 1 k+1 个节点时,其左右子树的节点个数必然小于等于 k k ,由归纳假设,如果 A A B B 都在右子树,则 l e f t = n u l l left=null ,并且 r i g h t right 是最近公共祖先,所以返回 r i g h t right 是正确的;如果 A A B B 都在左子树,推理类似;如果 A A B B 分别在两个子树中,那么递归两个子树时都不会返回null,此时最近公共祖先就是 r o o t root ,原因是 r o o t root 显然是公共祖先,并且无论怎么向下走一步,都不再是公共祖先。

发布了354 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/104958487