
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//root == p || root == q 时不能再往更深层找了, 否则会不满足公共祖先的要求
if(root == null || root == p || root == q) {
return root;//在二叉树递归算法中,root可以认为是递归过程中的当前节点
}
//递归在当前节点左右子树中寻找p或q
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
//说明在当前节点root的左子树找到了p右子树找到了q或者左子树找到了q右子树找到了p
if(left != null && right != null) {
return root; //那么当前节点root是最近公共祖先
}
//如果执行到这里,说明p,q肯定都在当前节点root的左子树一侧或者右子树一侧,
//并且p,q都在当前节点root的左子树一侧或者右子树一侧时,p和q不可能位于同一层
return left != null ? left : right;
}
}



















![[含文档+PPT+源码等]精品基于PHP实现的培训机构信息管理系统的设计与实现](https://img-blog.csdnimg.cn/img_convert/227e09cc8c57df5696bf5fa3e151696c.png)