-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path437. Path Sum III.go
65 lines (58 loc) · 1.23 KB
/
437. Path Sum III.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
// 解法一 带缓存 dfs
func pathSum(root *TreeNode, targetSum int) int {
prefixSum := make(map[int]int)
prefixSum[0] = 1
return dfs(root, prefixSum, 0, targetSum)
}
func dfs(root *TreeNode, prefixSum map[int]int, cur, sum int) int {
if root == nil {
return 0
}
cur += root.Val
cnt := 0
if v, ok := prefixSum[cur-sum]; ok {
cnt = v
}
prefixSum[cur]++
cnt += dfs(root.Left, prefixSum, cur, sum)
cnt += dfs(root.Right, prefixSum, cur, sum)
prefixSum[cur]--
return cnt
}
// 解法二
func pathSumIII(root *TreeNode, sum int) int {
if root == nil {
return 0
}
res := findPath437(root, sum)
res += pathSumIII(root.Left, sum)
res += pathSumIII(root.Right, sum)
return res
}
// 寻找包含 root 这个结点,且和为 sum 的路径
func findPath437(root *TreeNode, sum int) int {
if root == nil {
return 0
}
res := 0
if root.Val == sum {
res++
}
res += findPath437(root.Left, sum-root.Val)
res += findPath437(root.Right, sum-root.Val)
return res
}