第六章 二叉树 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;
};
路径总和
本题 又一次涉及到回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解
- 路径总和,和 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.从前序与中序遍历序列构造二叉树 一起做,思路一样的
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);
};