package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func demo(root *TreeNode, sum int, path []int, result *[][]int) {
if root.Left != nil {
demo(root.Left, sum-root.Val, append(path, root.Val), result)
}
if root.Right != nil {
demo(root.Right, sum-root.Val, append(path, root.Val), result)
}
if root.Left == nil && root.Right == nil && root.Val == sum {
// append是引用操作,不是值传递。会导致正确答案被后面的操作修改掉。
//*result = append(*result, append(path, sum))
tmp := make([]int, len(path)+1)
copy(tmp, append(path, sum))
*result = append(*result, tmp)
}
}
func pathSum(root *TreeNode, sum int) [][]int {
if root == nil {
return nil
}
result := make([][]int, 0)
path := make([]int, 0)
demo(root, sum, path, &result)
return result
}
func main() {
//node := TreeNode{1, &TreeNode{2, nil, nil}, nil}
node := TreeNode{1, nil, nil}
sum := pathSum(&node, 1)
fmt.Println(sum)
}