找树左下角的值
本地递归偏难,反而迭代简单属于模板题, 两种方法掌握一下
题目链接/文章讲解/视频讲解:https://programmercarl.com/0513.找树左下角的值.html
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var findBottomLeftValue = function(root) {
let result = root.val;
let maxDep = -Infinity;
const traverse = (node, depth) => {
if (node.left === null && node.right === null) {
if (maxDep < depth) {
maxDep = depth;
result = node.val;
}
return;
}
if (node.left) {
traverse(node.left, depth+1);
}
if (node.right) {
traverse(node.right, depth+1);
}
}
traverse(root, 0);
return result
};
路径总和
本题 又一次设计要回溯的过程,而且回溯的过程隐藏的还挺深,建议先看视频来理解
112. 路径总和,和 113. 路径总和ii 一起做了。 优先掌握递归法。
题目链接/文章讲解/视频讲解:https://programmercarl.com/0112.路径总和.html
这题自己写出跟题解不一样的递归,总算可以自己写出来了
function getTotal(node, total, target) {
if (node.left === null && node.right === null) {
total += node.val;
if (total === target) {
return true;
} else {
total -= node.val;
return false;
}
}
total += node.val
if (node.left) {
let flag = getTotal(node.left, total, target);
if (flag) {
return true;
}
}
if (node.right) {
let flag = getTotal(node.right, total, target);
if (flag) {
return true;
}
}
total -= node.val;
return false;
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
var hasPathSum = function(root, targetSum) {
if (root == null) return false;
let total = 0;
let flag = getTotal(root, total, targetSum);
return flag;
};
从中序与后序遍历序列构造二叉树
本题算是比较难的二叉树题目了,大家先看视频来理解。
106.从中序与后序遍历序列构造二叉树,105.从前序与中序遍历序列构造二叉树 一起做,思路一样的
题目链接/文章讲解/视频讲解:https://programmercarl.com/0106.从中序与后序遍历序列构造二叉树.html
这题好难,基本没思路
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
if (!inorder.length) return null;
let rootVal = postorder.pop();
let index = inorder.indexOf(rootVal);
let root = new TreeNode(rootVal);
root.left = buildTree(inorder.slice(0,index), postorder.slice(0,index));
root.right = buildTree(inorder.slice(index+1), postorder.slice(index,))
return root;
};
标签:node,right,return,val,随想录,二叉树,左下角,root,left
From: https://www.cnblogs.com/yuanyf6/p/18213972