LeetCode 437 Path Sum III DFS
阿新 • • 發佈:2022-05-20
Given the root
of a binary tree and an integer targetSum
, return the number of paths where the sum of the values along the path equals targetSum
.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
Solution
和以往的題目不同:只需要找到樹中的一條路徑即可。因此一個相對暴力的做法就是以每個節點為 \(root\)
現在對於每棵樹,我們用 \(dfs\) 來遞迴答案
點選檢視程式碼
/** * 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 { private: long long dfs(TreeNode* root, long long prev, int targetSum){ if(!root) return 0; long long cur = prev + root->val; return (cur==targetSum) + dfs(root->right, cur, targetSum) + dfs(root->left, cur, targetSum); } public: int pathSum(TreeNode* root, int targetSum) { if(!root) return 0; return dfs(root, 0, targetSum) + pathSum(root->left, targetSum) + pathSum(root->right, targetSum); } };