LeetCode  235.二叉搜索树的最近公共祖先_子树


​ https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/​

/**
* 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||root==p||root==q){
return root;
}
//p,q 的值都比根结点大,那么就从右子树找
if(p.val<root.val&&q.val<root.val){
return lowestCommonAncestor(root.left,p,q);
}
//p,q 的值都比根结点小,那么就从左子树找
if(p.val>root.val&&q.val>root.val){
return lowestCommonAncestor(root.right,p,q);
}
//找不到就在根结点上
return root;
}
}