/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root==null){
return null;
}
// 如果根和其中之一相同,那么根就是最低的公共祖先,另一者必然在根的左/右子树中
if(root==p||root==q){
return root;
}
// 如果返回的不为null,那么就是第一个等于p/q其中之一的节点
TreeNode left=lowestCommonAncestor(root.left,p,q);
TreeNode right=lowestCommonAncestor(root.right,p,q);
// p,q都存在于树中,所以不会全空
if(left!=null&&right!=null){
return root;
}else if(left!=null){
// right == null
return left;
}else{
return right;
}
}
}