面试题68 - II. 二叉树的最近公共祖先
说明:
·所有节点的值都是唯一的。
·p、q 为不同节点且均存在于给定的二叉树中。
思路:递归
根据题意可得,root、p、q一共有以下几种情况:
1、p 和 q在分别 root 的分别在左、右子树中,则root就是公共祖先;
2、p ,q都为root的左子节点,则返回lowestCommonAncestor(root.left,p,q);
3、p,q都是root的右子节点,那么返回lowestCommonAncestor(root.right,p,q);
递归过程:
(1)当root为空,或者p、q等于root时,返回root;
(2)当left 和 right同时为空 时,说明 root 的左 、右子树中都不包含 p,q ,则返回 null;
(3)当 left 为空 ,right 不为空时,p,q都不在 root 的左子树中,直接返回 right 。具体可分为两种情况:
1、p,q其中一个在 root 的 右子树 中,此时 right 指向 p,q其中一个;
2、p,q两节点都在 root的 右子树 中,此时的 right指向最近公共祖先节点 ;
(4)当 left 不为空 , right 为空时,原理同上;
(5)当 left 和 right同时不为空 时,说明 p, q分别在 root 的两侧 ,即分别在 左 / 右子树,因此 root 为最近公共祖先,返回 root。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p ,q);
if (left == null && right == null) {
return null;
}
if (left == null) {
return right;
}
if (right == null) {
return left;
}
return root;
}
}