题目地址:
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;
}
}
时间复杂度 ,空间 。
算法正确性证明:
函数的含义是在root为根的二叉树中寻找
和
的最近公共祖先(如果
和
都存在的话),否则,如果只存在
或
的话,就返回
或者
,都不存在则返回null。
数学归纳法。如果树只有 或 个节点时,结论正确。假设对 个节点时也对,当树有 个节点时,其左右子树的节点个数必然小于等于 ,由归纳假设,如果 和 都在右子树,则 ,并且 是最近公共祖先,所以返回 是正确的;如果 和 都在左子树,推理类似;如果 和 分别在两个子树中,那么递归两个子树时都不会返回null,此时最近公共祖先就是 ,原因是 显然是公共祖先,并且无论怎么向下走一步,都不再是公共祖先。