mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -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;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
@ -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<length; i++){
|
||||
let node = queue.shift();
|
||||
if(i===0){
|
||||
resNode = node.val;
|
||||
}
|
||||
node.left&&queue.push(node.left);
|
||||
node.right&&queue.push(node.right);
|
||||
}
|
||||
}
|
||||
return resNode;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user