leetcode 437. 路径总和 III

题解

递归,注意递归结束条件,cur == 0时不要结束递归,因为可能还有更长的路径和等于sum

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func pathSum(root *TreeNode, sum int) int {
if root == nil {
return 0
}
res := preTrav(root, sum)
res += pathSum(root.Left, sum)
res += pathSum(root.Right, sum)
return res
}

func preTrav(root *TreeNode, cur int) int {
if root == nil {
return 0
}
res := 0
cur -= root.Val
if cur == 0 {
res++
}
res += preTrav(root.Left, cur)
res += preTrav(root.Right, cur)
return res
}