【js刷题--树】JZ86 在二叉树中找到两个节点的最近公共祖先

描述
给定一棵二叉树(保证非空)以及这棵树上的两个节点对应的val值 o1 和 o2,请找到 o1 和 o2 的最近公共祖先节点。

基本思路
1、如果根节点为空,则返回空
2、如果左子树或者右子树为根节点,则返回根节点即可
3、如果非根节点,且两节点在左右子树两侧,则返回根节点
4、如果在某一侧,则一直递归,看某一侧哪个不为空,则递归哪一边

/*
 * 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 ) {
    // write code here
    if(root === null) return null
    //如果两个节点为根节点,则,两个节点本身为最近公共祖先
    if(root.val === o1 || root.val === o2) return root.val
    //定义出左右子树
    let left = lowestCommonAncestor(root.left,o1,o2)
    let right = lowestCommonAncestor(root.right,o1,o2)
    //如果两节点在两侧,则根节点为祖先
    if(left!=null&&right !=null) return root.val
    // 如果左子树有值,则最近公共祖先在左子树,否则,在右子树
    return left!==null?left:right
}
module.exports = {
    lowestCommonAncestor : lowestCommonAncestor
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值