Skip to content

Commit

Permalink
二叉树路径总和JavaScript版本
Browse files Browse the repository at this point in the history
  • Loading branch information
xllpiupiu committed May 29, 2021
1 parent 5512ccd commit b1b389d
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions problems/0112.路径总和.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};
```



Expand Down

0 comments on commit b1b389d

Please sign in to comment.