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
| // @Title: 路径总和 (Path Sum)
// @Author: 15816537946@163.com
// @Date: 2019-11-23 20:01:32
// @Runtime: 8 ms
// @Memory: 4.7 MB
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/*
func hasPathSum(root *TreeNode, sum int) bool {
if root == nil {
return false
}
sum -=root.Val
if root.Left == nil && root.Right == nil {
return sum == 0
}
return hasPathSum(root.Left,sum) || hasPathSum(root.Right,sum)
}
*/
func hasPathSum(root *TreeNode, sum int) bool {
if root == nil {
return false
}
sum -= root.Val
// 到达root的叶子节点
if root.Left == nil && root.Right == nil {
return sum == 0
}
return hasPathSum(root.Left, sum) || hasPathSum(root.Right, sum)
}
|