class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null || root==p || root==q) {//递归结束条件 注意这里用的是||
return root;// 方法的返回值为root, root值可以为p或者q或者null
}
//后序遍历 下面的left和right可以为p或者q或者null,因此下面的判断只要left!=null && right!=null 就说明找到了
TreeNode left = lowestCommonAncestor(root.left, p, q); // 这里是递归遍历到最左边
TreeNode right = lowestCommonAncestor(root.right, p, q); // 递归到最左边之后再递归到最右边
if(left == null && right == null) { // 若未找到节点 p 或 q
return null;
}else if(left == null && right != null) { // 若找到一个节点
return right;//之所以返回right,因为right!=null 说明right要么为q要么为p,为其中任意一个
}else if(left != null && right == null) { // 若找到一个节点
return left;
}else { //若找到两个结点
return root;
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}