题解 | #二叉搜索树的最近公共祖先#

二叉搜索树的最近公共祖先

https://www.nowcoder.com/practice/d9820119321945f588ed6a26f0a6991f

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 
 * @param p int整型 
 * @param q int整型 
 * @return int整型
 */
function lowestCommonAncestor( root ,  p ,  q ) {
    // write code here
    //递归实现
    //1.空节点没有祖先
    if(!root){
        return;
    }
    //2.当p和q小于这个节点,那么这个公共祖先在左子树中
    if(p < root.val&& q < root.val){
        return lowestCommonAncestor(root.left,p,q)
    }else if(p > root.val&&q > root.val){
        //3.当p和q都大于这个节点,那么这个公共祖先再右子树中
        return lowestCommonAncestor(root.right,p,q)
    }else{
        //4.当他们其中一个>=或者<=,一个节点的时候,那么他们公共祖先就是该接待你
        return root.val
    }
}
module.exports = {
    lowestCommonAncestor : lowestCommonAncestor
};

全部评论

相关推荐

牛客34884196...:你期望薪资4-5k,那确实可以重生了,但很难在深圳活下去
点赞 评论 收藏
分享
代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务