//解1
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// LCA 问题
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;
}
//解2
当二叉树 当前节点的左节点 一定小于当前节点 右节点一定大与当前节点 或相反,可以用下面的算法
if(root.val==p.val||root.val==q.val){
return root;
}
if (root.val > p.val &&root.val > q.val) {
return lowestCommonAncestor( root.right, p, q);
}
if (root.val < p.val &&root.val < q.val) {
return lowestCommonAncestor( root.left, p, q);
}
return root;
05-12
283
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-14
1134
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-28