牛客题霸——在二叉树中找到两个节点的最近公共祖先(Javascript)

一、题目地址

https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116?tpId=188&&tqId=38564&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

二、具体代码

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */

/**
 * 
 * @param root TreeNode类 
 * @param o1 int整型 
 * @param o2 int整型 
 * @return int整型
 */
function lowestCommonAncestor( root ,  o1 ,  o2 ) {
    //遇到叶子节点返回null
    if(root === null) {
        return null;
    }
    //如果p或q为根节点,则p或q为最近公共祖先
    if(root.val === o1 || root.val === o2) {
        return root.val;
    }
    // 在左子树寻找p和q的最近公共祖先
    let left = lowestCommonAncestor( root.left ,  o1 ,  o2 );
    // 在右子树寻找q和q的最近公共祖先
    let right = lowestCommonAncestor( root.right ,  o1 ,  o2 );
    // 如果p和q分属两侧,则根节点为最近公共祖先
    if(left !== null && right !== null) {
        return root.val;
    }
    // 如果左子树有值,则最近公共祖先在左子树,否则,在右子树
    return left !== null ? left : right;
}
module.exports = {
    lowestCommonAncestor : lowestCommonAncestor
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值