Skip to content

Commit 841406d

Browse files
committed
go: path sum iii
1 parent 134e524 commit 841406d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

go/path-sum-iii.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* type TreeNode struct {
6+
* Val int
7+
* Left *TreeNode
8+
* Right *TreeNode
9+
* }
10+
*/
11+
func pathSum(root *TreeNode, targetSum int) int {
12+
if root == nil {
13+
return 0
14+
}
15+
16+
return traversePathSum(root, targetSum, 0) + pathSum(root.Left, targetSum) + pathSum(root.Right, targetSum)
17+
}
18+
19+
func traversePathSum(root *TreeNode, targetSum int, sum int) int {
20+
if root == nil {
21+
return 0
22+
}
23+
24+
count := 0
25+
if root.Val+sum == targetSum {
26+
count++
27+
}
28+
29+
lCount := traversePathSum(root.Left, targetSum, sum+root.Val)
30+
rCount := traversePathSum(root.Right, targetSum, sum+root.Val)
31+
32+
return lCount + rCount + count
33+
}

0 commit comments

Comments
 (0)