mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-07 01:44:56 +08:00
42 lines
754 B
Go
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
|
|
}
|