1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) [][]int {
results := [][]int{}
re := []int{}
getNode(root, targetSum, re, &results)
return results
}
func getNode(root *TreeNode, targetSum int, re []int, res *[][]int) {
if root == nil {
return
}
lst := make([]int, len(re))
// 这里是重点,有时会覆盖掉了原来的,所以复制一份出来
re = append(re, root.Val)
copy(lst, re)
if root.Left == nil && root.Right == nil && root.Val == targetSum {
// 最后追加的时候,用复制出来的切片,如果修改追加为re,再res追加re。打印的也是正确的值,但最终结果却是错的
lst = append(lst, root.Val)
// 解引用
*res = append(*res, lst)
}
getNode(root.Left, targetSum - root.Val, re, res)
getNode(root.Right, targetSum - root.Val, re, res)
}
|