No. 112 - Path Sum
====


---
## [LeetCode 112 -- Path Sum](https://leetcode.com/problems/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 1.

```
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
```
---
### 解法
本題的目的是要尋找一顆 tree 從 root 到任一 leaf 的所有 nodes 的和是否有與 `targetSum` 相等。
從這題目的敘述我們可以想到的是就是用 depth first search 來解,用 DFS 來計算每一條 root-to-leaf 路徑的 nodes 總和,並在每條 path 走到最後的 node 加總完後,跟 `targetSum` 進行比較確認是否相同。
完整的程式如下:
```cpp=
/**
* 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:
bool dfs(TreeNode *node,int pathSum, int targetSum) {
if (!node)
return false;
if (!node->left && !node->right)
return pathSum + node->val == targetSum;
pathSum += node->val;
return dfs(node->left, pathSum, targetSum) || dfs(node->right, pathSum, targetSum);
}
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root, 0, targetSum);
}
};
```
我們宣告一個 `dfs` 函式來進行 DFS,每一次的 recursive 我們需要知道當前走訪到的 node 以及前面走過的 nodes 的總和 `pathSum`,同時也需要把我們最後需要比較的 `targetSum` 一路往下傳。
程式第 17 行當判別出 DFS 已經走到 leaf 則會跟 `targetSum` 進行比較確認是否相等。
程式第 20 行則是 dfs recursive 的做法,繼續走訪當前 node 的 left 跟 right child 直到走到 leaf。而最後我們只需要用 logic OR 來判斷是否存在一條 path 的總和與 `targetSum` 相等即可。
### 複雜度分析
我們需要走訪每個 nodes 所以時間複雜度為 $O(N)$。
我們需要存 `dfs` 的函式 stack 空間複雜度為 $O(H)$。