持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第10天,点击查看活动详情🚀🚀
前言
今天又是五道题,好在题目难度适中,并没有因此花四五个小时~
513. 找树左下角的值 - 力扣(LeetCode)
层序遍历
if(!root)
return root;
let queue = [root];
let res= [];
while(queue.length){
let len = queue.length;
for(let i = 0; i< len; i++){
let top = queue.shift();
if(i == 0){
res = top.val;
}
top.left && queue.push(top.left)
top.right && queue.push(top.right)
}
}
return res
这里层序遍历比递归要简单一点,层序遍历只要找到每层第一个出队的元素。
递归
if(!root)
return root;
let maxdepth = 0;
let depth = 1;
let res = 0;
const dfs = (root,depth) => {
if(root.left == null && root.right == null){
if(maxdepth < depth){
maxdepth = depth;
res = root.val ;
}
}
root.left && dfs(root.left,depth+1);
root.right && dfs(root.right,depth+1);
}
dfs(root,depth)
return res;
也没有多难,就是找到最大深度的那个没有子结点的结点,把它的值取出来即可。
收获
- 在层序遍历中,res的值是一直被代替的,而不是找到了最深那层后再进行操作
- 递归中,判断最大深度时,这里其实隐藏了回溯的过程,只不过把
depth+1写进了递归函数中dfs(root.left,depth+1);
112. 路径总和 - 力扣(LeetCode)
递归
var hasPathSum = function(root, targetSum) {
if(!root)
return false;
let flag = false;
const dfs = (root,sum) => {
console.log(sum)
if(!root.left && !root.right && sum == 0){
flag = true
}
root.left && dfs(root.left,sum-root.left.val);
root.right && dfs(root.right,sum-root.right.val);
}
dfs(root,targetSum-root.val);
return flag
};
注意:这里不是用求和的方式,而是逐级递减。还有最外层
dfs(root,targetSum-root.val);一定不要忘了减去root.val
113. 路径总和 II - 力扣(LeetCode)
递归
let path = [];
let res = [];
if(!root)
return [] ;
const dfs = (root,path,sum) => {
path.push(root.val)
if(sum == 0 && !root.left && !root.right ){
res.push([...path]);
return
}
if(root.left) {
dfs(root.left,path,sum - root.left.val) ;
path.pop()
}
if(root.right){
dfs(root.right,path,sum - root.right.val)
path.pop()
}
}
dfs(root,path,targetSum-root.val)
return res
收获
这道题看上去和上道题差不多,其实还是有一些细节需要牢记!!!
res.push([...path]);这里要用深拷贝的形式,否则后面的值都是一样的,因为
path是复杂数据类型,不能简单的直接赋值!!!- 这里的回溯不能隐藏起来了,每一层出来后要
path.pop()
106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
递归
var buildTree = function(inorder, postorder) {
if(!inorder.length)
return null
let val = postorder.pop();
let index = inorder.indexOf(val);
let root = new TreeNode(val);
root.left = buildTree(inorder.slice(0,index),postorder.slice(0,index))
root.right = buildTree(inorder.slice(index + 1), postorder.slice(index))
return root;
};
思路
这道题就是看起来难,但只要不要畏惧它,其实还是和之前的题型难度差不多。
这里直接用卡哥的步骤,再配合自己画图,很好理解的~
- 第一步:如果数组大小为零的话,说明是空节点了。
- 第二步:如果不为空,那么取
后序数组最后一个元素作为节点元素。 - 第三步:找到后序数组最后一个元素在
中序数组的位置,作为切割点 - 第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
- 第五步:切割后序数组,切成后序左数组和后序右数组
- 第六步:递归处理左区间和右区间
105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)
递归
var buildTree = function(preorder, inorder) {
if (!preorder.length) return null;
const rootVal = preorder.shift();
const index = inorder.indexOf(rootVal);
const root = new TreeNode(rootVal);
root.left = buildTree(preorder.slice(0, index), inorder.slice(0, index));
root.right = buildTree(preorder.slice(index), inorder.slice(index + 1));
return root;
};
这道题可以说基本上和上道题一模一样了~
收获
- 这里处理边界的情况是
if (!preorder.length) return null;
一定要有返回值 null!!
- slice这个方法,是左闭右开的!别被坑了哈