DFS 前缀和
注意下面的代码中 111 行代码 不要和 222 行代码互换位置,因为我们所求的是当前节点如果计入答案的情况下,是否在之前的节点中存在相对应的前缀和,如果我们提前将当前节点存入 map 中的话,那么我们的代码在targetsum 为 0 的情况下就会多次计入重复答案
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, targetSum int) (ans int) {
preSum := map[int]int{0: 1}
var dfs func(*TreeNode, int)
dfs = func(node *TreeNode, curr int) {
if node == nil {
return
}
curr += node.Val
ans += preSum[curr-targetSum] //111行
preSum[curr]++ //222行
dfs(node.Left, curr)
dfs(node.Right, curr)
preSum[curr]--
return
}
dfs(root, 0)
return
}
暴力 DFS
枚举所有情况
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func rootSum(root *TreeNode, targetSum int) (res int) {
if root == nil {
return
}
val := root.Val
if val == targetSum {
res++
}
res += rootSum(root.Left, targetSum-val)
res += rootSum(root.Right, targetSum-val)
return
}
func pathSum(root *TreeNode, targetSum int) int {
if root == nil {
return 0
}
res := rootSum(root, targetSum)
res += pathSum(root.Left, targetSum)
res += pathSum(root.Right, targetSum)
return res
}