---
# System prepended metadata

title: '[LeetCode 113. Path Sum II ](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3838/)'

---

# [LeetCode 113. Path Sum II ](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3838/)
### Daily challenge Aug 4, 2021 (MEDIAN)

>Given the `root` of a binary tree and an integer `targetSum`, return all **root-to-leaf** paths where each path's sum equals targetSum.
>
>A **leaf** is a node with no children.

![](https://i.imgur.com/LT7VHBJ.png)

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

![](https://i.imgur.com/idEnsKX.png)

:::info
**Example 2:**
**Input:** root = [1,2,3], targetSum = 5
**Output:** []
:::

:::info
**Example 3:**
**Input:** root = [1,2], targetSum = 0
**Output:** []
:::


:::warning
**Constraints:**
* The number of nodes in the tree is in the range [0, 5000].
* -1000 <= Node.val <= 1000
* -1000 <= targetSum <= 1000
:::

---



### Approach 1 : DFS :bulb: 
**`8 ms ( 81.38% )`** **`O()`**

使用 `DFS` 從 `root` 搜尋到 `leaf` ，再判斷 `sum` 是否等於 `targetSum`。

* 使用 `current` 紀錄當前 `path`。
>```cpp=15
>        current.push_back(root->val);
>```
>```cpp=23
>        current.pop_back();
>```
>
* 若 **`root->left == NULL && root->right == NULL`** 表示該點為 `leaf node`。
---> **`sum == targetSum`** -> 找到一個答案。

```cpp=1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root, int targetSum, vector<vector<int>>& ans, vector<int>& current, int sum){
        current.push_back(root->val);
        
        if(root->left == NULL && root->right == NULL){
            if(sum + root->val == targetSum)    ans.push_back(current);
        }
        if(root->left != NULL)  dfs(root->left, targetSum, ans, current, sum + root->val);
        if(root->right != NULL) dfs(root->right, targetSum, ans, current, sum + root->val);
            
        current.pop_back();
    }
    
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        vector<vector<int>> ans;
        vector<int> current;
        
        if(root == NULL)    return ans;
        dfs(root, targetSum, ans, current, 0);
        
        return ans;
    }
};
```