From e98373b98ce5d27783990eeb8e44b61ad6fe0a01 Mon Sep 17 00:00:00 2001 From: ductnn Date: Mon, 18 Dec 2023 12:43:00 +0700 Subject: [PATCH] add sol --- .../437.PathSumIII/pathSumIII.go | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 leetcode/leetcode75/BinaryTree-DFS/437.PathSumIII/pathSumIII.go diff --git a/leetcode/leetcode75/BinaryTree-DFS/437.PathSumIII/pathSumIII.go b/leetcode/leetcode75/BinaryTree-DFS/437.PathSumIII/pathSumIII.go new file mode 100644 index 0000000..97e08d3 --- /dev/null +++ b/leetcode/leetcode75/BinaryTree-DFS/437.PathSumIII/pathSumIII.go @@ -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)) +}