【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
};

版权声明:本文为weixin_49487698原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。