Contents

# 112. Path Sum

## 題目 :

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

### Example :

Note

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true

Example 2:

Input: root = [1,2,3], targetSum = 5 Output: false

Example 3:

Input: root = [1,2], targetSum = 0 Output: false

#### 解題思路 :

• 這題需要我把檢查是否有任何一個path的和等於他給的targetSum
• 這題考察的其實的不外乎就是對dfs的概念，加上若是用recursive的方式會更簡潔，所以一方面也考察對於recursive code的掌握度，誰作為回傳值or誰作為argument…等
• 解法1是我一開始的答案，非常直觀的寫法，且time complexity是O(n)
• 看完解法1可以繼續看我從討論區得到的解法2，這個解法就更簡潔了，是利用targetSum進行減法去做檢查，是不是更高明了呢!? 趕快學起來!

### Recursive解法-1

• time complexity: O(n) , space complexity: O(1)

Runtime: 4 ms, faster than 91.44% of Go online submissions for Path Sum.

 `````` 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 `````` ``````/** * 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 } res := false var sum int findTargetSum(root, &res, sum, targetSum) return res } func findTargetSum(node *TreeNode, res *bool, sum int, targetSum int) { if *res == true { return } sum += node.Val if node.Left == nil && node.Right == nil { if targetSum == sum { *res = true } } if node.Left != nil { findTargetSum(node.Left,res,sum, targetSum) } if node.Right != nil { findTargetSum(node.Right,res,sum, targetSum) } return } ``````

### Recursive解法-2

• time complexity: O(n) , space complexity: O(1)

Runtime: 4 ms, faster than 91.44% of Go online submissions for Path Sum.

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 `````` ``````/** * 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) } ``````