题目:
剑指 Offer 34. 二叉树中和为某一值的路径
思路
采用回溯方法:即深度优先搜索算法–DFS
图画的有些乱,下次会注意的。
代码
var pathSun=function(root,sum)
{
if(!root)
{
return []
}
let curSum=0;
let res=[];
let path=[];
findPath(root,sum,curSum,res,path)
return res;
}
var findPath=function(root,sum,curSum,res,path)
{
path.push(root.val)
curSum+=root.val;
if(curSum==sum&&!root.left&&!root.right)
{
//slice(0)复制数组
res.push(path.slice(0))
}
if (root.left) {
findPath(root.left, sum, curSum, res, path)
}
if (root.right) {
findPath(root.right, sum, curSum, res, path)
}
//pop()删除数组最后一个元素
path.pop()
}