leetcode-112 路径总和

112. 路径总和

难度: 简单




  • 递归求解即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {

if root == nil {
return false
}

if root.Left == nil && root.Right == nil {
return targetSum == root.Val
}

return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val)

}

文章目录