//本题中的路径指的是从根结点到叶节点
var tree={
root:1,
rchild:{
root:2,
rchild:null,
lchild:{
root:1,
rchild:null,
lchild:null,
}
},
lchild:{
root:3,
rchild:null,
lchild:null
}
}
function findPath(tree,Num){
var result = []
if(tree.root===null){
return result
}
dnsfind(tree,Num,0,[],result)
return result
}
function dnsfind(tree,Num,currentSum,path,result){
currentSum+=tree.root
path.push(tree.root)
//当叶节点满足要求
if(currentSum===Num&&tree.rchild===null&&tree.lchild===null){
result.push(path.slice(0))
//因为path是引用类型,遍历结束后,path会pop会根结点,也就是变为[],如果这里直接存储path的话,最后也会变成[]
}
//前序遍历
if(tree.lchild!==null){
dnsfind(tree.lchild,Num,currentSum,path,result)
}
if(tree.rchild!==null){
dnsfind(tree.rchild,Num,currentSum,path,result)
}
//当到达叶节点但却不满足要求时,pop会到上一节点,继续遍历
path.pop()
}
console.log(findPath(tree,4)) //[[1,3],[1,2,1]]
二叉树找到和为n的所有路径
最新推荐文章于 2023-03-15 20:40:53 发布