Skip to content

Commit b1b389d

Browse files
committed
二叉树路径总和JavaScript版本
1 parent 5512ccd commit b1b389d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

problems/0112.路径总和.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -524,6 +524,62 @@ let pathSum = function (root, targetSum) {
524524
};
525525
```
526526

527+
0112 路径总和
528+
```javascript
529+
var hasPathSum = function(root, targetSum) {
530+
//递归方法
531+
// 1. 确定函数参数
532+
const traversal = function(node,count){
533+
// 2. 确定终止条件
534+
if(node.left===null&&node.right===null&&count===0){
535+
return true;
536+
}
537+
if(node.left===null&&node.right===null){
538+
return false;
539+
}
540+
//3. 单层递归逻辑
541+
if(node.left){
542+
if(traversal(node.left,count-node.left.val)){
543+
return true;
544+
}
545+
}
546+
if(node.right){
547+
if(traversal(node.right,count-node.right.val)){
548+
return true;
549+
}
550+
}
551+
return false;
552+
}
553+
if(root===null){
554+
return false;
555+
}
556+
return traversal(root,targetSum-root.val);
557+
};
558+
```
559+
113 路径总和
560+
```javascript
561+
var pathSum = function(root, targetSum) {
562+
//递归方法
563+
let resPath = [],curPath = [];
564+
// 1. 确定递归函数参数
565+
const travelTree = function(node,count){
566+
curPath.push(node.val);
567+
count-=node.val;
568+
if(node.left===null&&node.right===null&&count===0){
569+
resPath.push([...curPath]);
570+
}
571+
node.left&&travelTree(node.left,count);
572+
node.right&&travelTree(node.right,count);
573+
let cur = curPath.pop();
574+
count-=cur;
575+
}
576+
if(root===null){
577+
return resPath;
578+
}
579+
travelTree(root,targetSum);
580+
return resPath;
581+
};
582+
```
527583

528584

529585

0 commit comments

Comments
 (0)