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: 2020-06-25 07:15:36
// @Runtime: 8 ms
// @Memory: 4.8 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)
}