添加新题目
This commit is contained in:
41
二叉树/路径总和III/main.go
Normal file
41
二叉树/路径总和III/main.go
Normal file
@@ -0,0 +1,41 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user