42 lines
953 B
Go
42 lines
953 B
Go
|
|
package main
|
||
|
|
|
||
|
|
type TreeNode struct {
|
||
|
|
Val int
|
||
|
|
Left *TreeNode
|
||
|
|
Right *TreeNode
|
||
|
|
}
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
|
||
|
|
}
|
||
|
|
func pathSum(root *TreeNode, targetSum int) int {
|
||
|
|
if root == nil {
|
||
|
|
return 0
|
||
|
|
}
|
||
|
|
if root.Left == nil && root.Right == nil && root.Val == targetSum {
|
||
|
|
return 1
|
||
|
|
}
|
||
|
|
hash := make(map[int]int)
|
||
|
|
var culcalute func(root *TreeNode, hash map[int]int, total int, targetSum int) int
|
||
|
|
culcalute = func(roottmp *TreeNode, hash map[int]int, total int, targetSum int) int {
|
||
|
|
if roottmp == nil {
|
||
|
|
return 0
|
||
|
|
}
|
||
|
|
restmp := 0
|
||
|
|
hashtmp := make(map[int]int)
|
||
|
|
for k, v := range hash {
|
||
|
|
hashtmp[k] = v
|
||
|
|
}
|
||
|
|
totalnum := total + roottmp.Val
|
||
|
|
if value, ok := hash[totalnum-targetSum]; ok {
|
||
|
|
restmp = restmp + value
|
||
|
|
}
|
||
|
|
hashtmp[totalnum]++
|
||
|
|
res := culcalute(roottmp.Left, hashtmp, totalnum, targetSum) + culcalute(roottmp.Right, hashtmp, totalnum, targetSum) + restmp
|
||
|
|
return res
|
||
|
|
}
|
||
|
|
hash[0]++
|
||
|
|
result := culcalute(root, hash, 0, targetSum)
|
||
|
|
return result
|
||
|
|
}
|