-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path437.路径总和-iii.go
69 lines (68 loc) · 1.45 KB
/
437.路径总和-iii.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* @lc app=leetcode.cn id=437 lang=golang
*
* [437] 路径总和 III
*
* https://leetcode-cn.com/problems/path-sum-iii/description/
*
* algorithms
* Easy (49.84%)
* Likes: 151
* Dislikes: 0
* Total Accepted: 6.2K
* Total Submissions: 12.5K
* Testcase Example: '[10,5,-3,3,2,null,11,3,-2,null,1]\n8'
*
* 给定一个二叉树,它的每个结点都存放着一个整数值。
*
* 找出路径和等于给定数值的路径总数。
*
* 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
*
* 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
*
* 示例:
*
* root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
*
* 10
* / \
* 5 -3
* / \ \
* 3 2 11
* / \ \
* 3 -2 1
*
* 返回 3。和等于 8 的路径有:
*
* 1. 5 -> 3
* 2. 5 -> 2 -> 1
* 3. -3 -> 11
*
*
*/
/**
* 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
}
return Sum(root, sum) + pathSum(root.Left, sum) + pathSum(root.Right, sum)
}
func Sum(node *TreeNode, sum int) int {
if node == nil {
return 0
}
res := 0
if node.Val == sum {
res += 1
}
res += Sum(node.Left, sum-node.Val) + Sum(node.Right, sum-node.Val)
return res
}