二叉树的最近公共祖先

如果当前节点是p(或q),最近公共祖先就是当前节点(或q)

如果当前节点是null,最近公共祖先就是null

如果当前节点的左子树的公共祖先节点不为空并且右子树不为空,那么当前节点为最近公共祖先

如果当前节点左子树返回空,说明左子树中没有p和q去右子树找,右边同理


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == q || root == p) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null) {
return right;
}
if (right == null) {
return left;
}
return root;
}
}