路径总和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]
}

 

 二叉树的建立:https://www.cnblogs.com/-citywall123/p/16434923.html

posted @ 2022-06-29 21:53  知道了呀~  阅读(52)  评论(0编辑  收藏  举报