diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index b4a3f38b..4ccd8912 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -524,6 +524,62 @@ let pathSum = function (root, targetSum) { }; ``` +0112 路径总和 +```javascript +var hasPathSum = function(root, targetSum) { + //递归方法 + // 1. 确定函数参数 + const traversal = function(node,count){ + // 2. 确定终止条件 + if(node.left===null&&node.right===null&&count===0){ + return true; + } + if(node.left===null&&node.right===null){ + return false; + } + //3. 单层递归逻辑 + if(node.left){ + if(traversal(node.left,count-node.left.val)){ + return true; + } + } + if(node.right){ + if(traversal(node.right,count-node.right.val)){ + return true; + } + } + return false; + } + if(root===null){ + return false; + } + return traversal(root,targetSum-root.val); +}; +``` +113 路径总和 +```javascript +var pathSum = function(root, targetSum) { + //递归方法 + let resPath = [],curPath = []; + // 1. 确定递归函数参数 + const travelTree = function(node,count){ + curPath.push(node.val); + count-=node.val; + if(node.left===null&&node.right===null&&count===0){ + resPath.push([...curPath]); + } + node.left&&travelTree(node.left,count); + node.right&&travelTree(node.right,count); + let cur = curPath.pop(); + count-=cur; + } + if(root===null){ + return resPath; + } + travelTree(root,targetSum); + return resPath; +}; +``` diff --git a/problems/0513.找树左下角的值.md b/problems/0513.找树左下角的值.md index 5c9613e5..97464e3d 100644 --- a/problems/0513.找树左下角的值.md +++ b/problems/0513.找树左下角的值.md @@ -298,6 +298,53 @@ class Solution: ``` Go: +JavaScript: +1. 递归版本 +```javascript +var findBottomLeftValue = function(root) { + //首先考虑递归遍历 前序遍历 找到最大深度的叶子节点即可 + let maxPath = 0,resNode = null; + // 1. 确定递归函数的函数参数 + const dfsTree = function(node,curPath){ + // 2. 确定递归函数终止条件 + if(node.left===null&&node.right===null){ + if(curPath>maxPath){ + maxPath = curPath; + resNode = node.val; + } + // return ; + } + node.left&&dfsTree(node.left,curPath+1); + node.right&&dfsTree(node.right,curPath+1); + } + dfsTree(root,1); + return resNode; +}; +``` +2. 层序遍历 +```javascript +var findBottomLeftValue = function(root) { + //考虑层序遍历 记录最后一行的第一个节点 + let queue = []; + if(root===null){ + return null; + } + queue.push(root); + let resNode; + while(queue.length){ + let length = queue.length; + for(let i=0; i