-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
47 lines (38 loc) · 900 Bytes
/
main.go
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func pathSum(root *TreeNode, targetSum int) [][]int {
if root == nil {
return nil
}
var result [][]int
collectPaths(root, &result, []int{}, targetSum, root.Val)
return result
}
func collectPaths(root *TreeNode, result *[][]int, arr []int, targetSum, currSum int) {
if root == nil {
return
}
// currSum += root.Val
if root.Left == nil && root.Right == nil {
if targetSum == currSum {
arr = append(arr, root.Val)
*result = append(*result, arr)
}
return
}
check := make([]int, len(arr))
if root.Left != nil {
copy(check, arr)
collectPaths(root.Left, result, append(check, root.Val), targetSum, currSum+root.Left.Val)
}
if root.Right != nil {
copy(check, arr)
collectPaths(root.Right, result, append(check, root.Val), targetSum, currSum+root.Right.Val)
}
}