235. 二叉搜索树的最近公共祖先
相对于 二叉树的最近公共祖先 本题就简单一些了,因为 可以利用二叉搜索树的特性无需全部遍历。特点:当前节点在p,q节点之前则必为最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
//当前节点大于p,q节点值往当前节点左子树遍历
if(root.val > p.val && root.val > q.val){
TreeNode left = lowestCommonAncestor(root.left,p,q);
if(left != null){
return left;
}
}
//当前节点小于p,q节点值往当前节点右子树遍历
if(root.val < q.val && root.val < p.val){
TreeNode right = lowestCommonAncestor(root.right,p,q);
if(right != null){
return right;