题目描述:
解题思路:
思路:分别递归的去左右子树中找,如果左右子树的返回值都不为NULL,说明当前结点就是两个结点公共祖先。然后递归左右子树,左子树为空,返回右子树;右子树为空,返回左子树。如此递归即可找到答案
代码实现:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return root;
}
if (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 root;
} else if (left != null) {
return left;
} else if (right != null) {
return right;
}
return null;
}