力扣---2020.9.27

carroll18發表於2020-12-17

235. 二叉搜尋樹的最近公共祖先

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val==root.val){
            return p;
        } 
        if (q.val==root.val){
            return q;
        }
        if (p.val > root.val && q.val > root.val) {
            return lowestCommonAncestor(root.right,p,q);
        }else if (p.val < root.val && q.val < root.val) {
            return lowestCommonAncestor(root.left,p,q);
        }else{
            return root;
        }
    }
}
class Solution {
    TreeNode res = null;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        
        lca(root, p , q);
        return res;
    }
    
    public void lca(TreeNode root, TreeNode p , TreeNode q){
        if((root.val - p.val)*(root.val - q.val) <= 0){
            res = root;
        }else if(root.val < p.val && root.val < q.val){
            lca(root.right, p , q);
        }else{
            lca(root.left, p , q);
        }
    }
}

你知道的越多,你不知道的越多。