刷题日记:二叉树的最近公共祖先

该文章提供了一个解决方案,用于在二叉树中找到两个给定节点的最低公共祖先。通过深度优先搜索遍历树,存储每个节点的父节点,并回溯找到两个节点到根节点的路径,然后找出这两个路径的第一个交点,即为最近公共祖先。
摘要由CSDN通过智能技术生成
题目描述:

在这里插入图片描述

leetcode236. 二叉树的最近公共祖先

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {TreeNode}
 */
var lowestCommonAncestor = function(root, p, q) {
    // 二叉树的最大公共祖先,
    // 将每个节点的父节点用map记录下来
    // 从p节点往回沿着父节点遍历到根节点,将遍历的节点路径保存在一个数组reverse_path_p中作为到p节点到root的路径
    // 再从q节点往回沿着父节点遍历到根节点,第一个存在于reverse_path_p中的节点便是最大公共祖先
    let map = new Map();
    let reverse_path_p = [];
    let res = null;
    const dfs = function(root){
        if(!root) return 
        if(root.left){ // 将每个节点的父节点保存起来
            map.set(root.left.val,root)
        }
        if(root.right){ // 将每个节点的父节点保存起来
            map.set(root.right.val,root)
        }
        dfs(root.left)
        dfs(root.right)
    }
    dfs(root)
    while(p){ // 寻找p 到 root 的路径
        reverse_path_p.push(p.val)
        p = map.get(p.val)
    }
    while(q){ // 从q 到 root 的路径中找第一个出现在q到root路径中的节点
        if(reverse_path_p.includes(q.val)){
            res = q
            break
        }
        q = map.get(q.val)
    }
    return res    
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值