add new solutions
This commit is contained in:
parent
886b5e0a8e
commit
67cad91898
47 changed files with 1549 additions and 1 deletions
36
solutions/4/q437/solution.go
Normal file
36
solutions/4/q437/solution.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package q437
|
||||
|
||||
type TreeNode struct {
|
||||
Val int
|
||||
Left *TreeNode
|
||||
Right *TreeNode
|
||||
}
|
||||
|
||||
func count(node *TreeNode, prefix []int, target int) int {
|
||||
if node == nil {
|
||||
return 0
|
||||
}
|
||||
if len(prefix) > 0 {
|
||||
prefix = append(prefix, node.Val+prefix[len(prefix)-1])
|
||||
} else {
|
||||
prefix = append(prefix, node.Val)
|
||||
}
|
||||
|
||||
cnt := 0
|
||||
for i := range len(prefix) - 1 {
|
||||
if prefix[len(prefix)-1]-prefix[i] == target {
|
||||
cnt++
|
||||
}
|
||||
}
|
||||
if prefix[len(prefix)-1] == target {
|
||||
cnt++
|
||||
}
|
||||
|
||||
return cnt + count(node.Left, prefix, target) + count(node.Right, prefix, target)
|
||||
}
|
||||
|
||||
func pathSum(root *TreeNode, targetSum int) int {
|
||||
return count(root, nil, targetSum)
|
||||
}
|
||||
|
||||
var _ = pathSum
|
||||
Loading…
Add table
Add a link
Reference in a new issue