-
Notifications
You must be signed in to change notification settings - Fork 0
/
path-sum.go
48 lines (43 loc) · 825 Bytes
/
path-sum.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
48
package main
import (
"fmt"
)
type treeNode struct {
Val int
left *treeNode
right *treeNode
}
func hasPathSum(root *treeNode, sum int) bool {
if root != nil {
for _, p := range pathSum(root) {
if sum == p {
return true
}
}
}
return false
}
func pathSum(node *treeNode) []int {
if node == nil {
return nil
}
path := []int{}
if node.left != nil {
for _, p := range pathSum(node.left) {
path = append(path, node.Val+p)
}
}
if node.right != nil {
for _, p := range pathSum(node.right) {
path = append(path, node.Val+p)
}
}
if node.left == nil && node.right == nil {
path = append(path, node.Val)
}
return path
}
func main() {
tree := &treeNode{5, &treeNode{4, &treeNode{11, &treeNode{7, nil, nil}, &treeNode{2, nil, nil}}, nil}, nil}
fmt.Println(hasPathSum(tree, 22))
}