Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Dec 18, 2023
1 parent 6a73708 commit e98373b
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions leetcode/leetcode75/BinaryTree-DFS/437.PathSumIII/pathSumIII.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"fmt"
)

/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/

type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}

func pathSum(root *TreeNode, targetSum int) int {
cnt := map[int]int{0: 1}
var dfs func(*TreeNode, int) int
dfs = func(root *TreeNode, sum int) int {
if root == nil {
return 0
}
sum += root.Val
result := cnt[sum-targetSum]
cnt[sum]++
result += dfs(root.Left, sum) + dfs(root.Right, sum)
cnt[sum]--
return result
}

return dfs(root, 0)
}

func main() {
// Define the trees
root := &TreeNode{
Val: 10,
Left: &TreeNode{
Val: 5,
Left: &TreeNode{Val: 3},
Right: &TreeNode{
Val: 2,
Right: &TreeNode{Val: 1},
},
},
Right: &TreeNode{
Val: -3,
Right: &TreeNode{Val: 11},
},
}
targetSum := 8

fmt.Println(pathSum(root, targetSum))
}

0 comments on commit e98373b

Please sign in to comment.