Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upGitHub is where the world builds software
Millions of developers and companies build, ship, and maintain their software on GitHub — the largest and most advanced development platform in the world.
路径总和 II-113 #27
路径总和 II-113 #27
Comments
|
data.json {
"code": 1,
"children": [
{
"code": 2,
"children": [
{
"code": 5,
"children": [
{
"code": 7
},
{
"code": 8
}
]
}
]
},
{
"code": 3,
"children": [
{
"code": 12,
"children": [
{
"code": 13
},
{
"code": 15
}
]
},
{
"code": 90,
"children": [
{
"code": 99
},
{
"code": 91
},
{
"code": 78
},
{
"code": 66
},
{
"code": 16,
"children": [
{
"code": 74,
"children": [
{
"code": 73,
"children": [
{
"code": 70,
"children": [
{
"code": 61
},
{
"code": 62
},
{
"code": 63,
"children": [
{
"code": 888
},
{
"code": 999,
"children": [
{
"code": 777
},
{
"code": 222
},
{
"code": 111
}
]
},
{
"code": 555
}
]
}
]
}
]
}
]
}
]
}
]
}
]
},
{
"code": 4,
"children": [
{
"code": 21,
"children": [
{
"code": 26
},
{
"code": 95
},
{
"code": 75
}
]
},
{
"code": 36,
"children": [
{
"code": 38,
"children": [
{
"code": 39
}
]
}
]
}
]
}
]
}index.js const data = require('./data.json')
function isChildren(node){
return node.children?true:false
}
var pathCode = function(node, code,key) {
const pathes = [];
_pathCode(node, code, pathes, [],key);
return pathes;
};
function _pathCode(node, code, pathes, path,key) {
path = [...path, node[key]];
if (node[key]===code){
pathes.push(...path)
return
}
if (isChildren(node)){
for (let i=0;i<node.children.length;i++){
_pathCode(node.children[i],code,pathes,path,key)
}
}
}
const paths = pathCode(data,555,'code') |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
典型的可以用 DFS 来解决的问题,定义一个 search 方法并且参数里带一个用来收集路径的 paths 数组,每当到达叶子节点(没有 left 也没有 right),就计算一把路径的总和,如果等于目标值就 push 到结果数组里。(注意这里要浅拷贝一下,防止下面的计算污染这个数组)
任何一个节点处理完成时,都要把当前节点 pop 出 paths 数组。