Files
LeetCode-Go/leetcode/0437.Path-Sum-III/437. Path Sum III.go
2020-08-07 17:06:53 +08:00

42 lines
754 B
Go

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
* }
*/
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
}