代码随想录算法训练营第16天 | 找树左下角的值、路径总和、从中序与后序遍历序列构造二叉树

二叉树相关算法问题解析

第六章 二叉树 part04

找树左下角的值

题目链接/文章讲解/视频讲解:https://programmercarl.com/0513.%E6%89%BE%E6%A0%91%E5%B7%A6%E4%B8%8B%E8%A7%92%E7%9A%84%E5%80%BC.html

var findBottomLeftValue = function (root) {
    const dfs = (root, height) => {
        if (!root) {
            return;
        }
        height++;
        dfs(root.left, height);
        dfs(root.right, height);
        if (height > curHeight) {
            curHeight = height;
            curVal = root.val;
        }
    }

    let curHeight = 0;
    dfs(root, 0);
    return curVal;
};

路径总和

本题 又一次涉及到回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解

  1. 路径总和,和 113. 路径总和ii 一起做了。 优先掌握递归法。

题目链接/文章讲解/视频讲解:https://programmercarl.com/0112.%E8%B7%AF%E5%BE%84%E6%80%BB%E5%92%8C.html

var hasPathSum = function (root, targetSum) {
    if (!root) return false
    if (!root.left && !root.right) {
        return targetSum === root.val
    }
    return hasPathSum(root.left, targetSum - root.val)
        || hasPathSum(root.right, targetSum - root.val)
};

从中序与后序遍历序列构造二叉树

本题算是比较难的二叉树题目了,大家先看视频来理解。

106.从中序与后序遍历序列构造二叉树,105.从前序与中序遍历序列构造二叉树 一起做,思路一样的

题目链接/文章讲解/视频讲解:https://programmercarl.com/0106.%E4%BB%8E%E4%B8%AD%E5%BA%8F%E4%B8%8E%E5%90%8E%E5%BA%8F%E9%81%8D%E5%8E%86%E5%BA%8F%E5%88%97%E6%9E%84%E9%80%A0%E4%BA%8C%E5%8F%89%E6%A0%91.html

var buildTree = function (inorder, postorder) {
    const build = (inStart, inEnd, postStart, postEnd) => {
        if (postStart > postEnd) return null;
        // 当前子树的根节点是 postorder[postEnd]
        const curValue = postorder[postEnd];
        const curHead = new TreeNode(curValue);
        // 找到根节点在 inorder 中的位置
        const index = inorder.indexOf(curValue);
        const leftSize = index - inStart;
        // 递归构建左子树
        curHead.left = build(inStart, index - 1, postStart, postStart + leftSize - 1);
        // 递归构建右子树
        curHead.right = build(index + 1, inEnd, postStart + leftSize, postEnd - 1);
        return curHead;
    }

    return build(0, inorder.length - 1, 0, postorder.length - 1);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值