第一种情况:二叉搜索树
因为是二叉搜索树所以左边一定比右边小,正负号解决问题(这个想法太秀了)
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root != null) {
if ((p.val - root.val) * (q.val - root.val) <= 0) return root;
else root = p.val > root.val ? root.right : root.left;
}
return root;
}
第二种情况:一般的二叉树
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null || root == p || root == q) 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;//找到两个
}
}
大概思路就是递归