其他分享
首页 > 其他分享> > 路径总和II

路径总和II

作者:互联网

 

 https://leetcode.cn/problems/path-sum-ii/

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, targetSum int) [][]int {
    stack:=make([]int,0)
    ways=make([][]int,0)
    dfs(root,0,targetSum,stack)
    return ways
}
var ways [][]int
func dfs(now *TreeNode,ans,target int,stack []int){
    if now==nil{//递归出口,可能有正数,也可能有负数
        return 
    }
   
    ans=ans+now.Val
    stack=append(stack,now.Val)
    if ans==target&&now.Left==nil&&now.Right==nil{//只有到叶子节点,并且和为target才可以
        tmp:=make([]int,len(stack))
        copy(tmp,stack)
        ways=append(ways,tmp)
    }
    dfs(now.Left,ans,target,stack)
    dfs(now.Right,ans,target,stack)
    ans=ans-now.Val
    stack=stack[:len(stack)-1]
}

 

标签:TreeNode,int,路径,II,ways,ans,now,stack,总和
来源: https://www.cnblogs.com/-citywall123/p/16425057.html