-
Notifications
You must be signed in to change notification settings - Fork 4
/
solution.go
45 lines (40 loc) · 903 Bytes
/
solution.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
package main
import "fmt"
// TreeNode is a binary tree node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func pathSum(root *TreeNode, sum int) [][]int {
var paths [][]int
var current []int
findPaths(root, sum, current, &paths)
return paths
}
func findPaths(root *TreeNode, sum int, current []int, paths *[][]int) {
if root == nil {
return
}
current = append(current, root.Val)
if root.Val == sum && root.Left == nil && root.Right == nil {
*paths = append(*paths, current)
return
}
findPaths(root.Left, sum-root.Val, current, paths)
findPaths(root.Right, sum-root.Val, current, paths)
}
func main() {
tree := &TreeNode{1,
&TreeNode{2,
&TreeNode{4,
&TreeNode{7, nil, nil},
nil},
&TreeNode{5, nil, nil}},
&TreeNode{3,
&TreeNode{6,
&TreeNode{8, nil, nil},
&TreeNode{9, nil, nil}},
nil}}
fmt.Printf("%#v", pathSum(tree, 14))
}