【树+前缀和】437. 路径总和 III——思路解释
1.暴力法——深度优先搜索
思路:
逐个遍历树的每个节点
从该节点开始遍历其左右子树,并累加求和
如果当前的和等于targetSum,则ans++
该种方法的时间复杂度为 O ( n 2 ) O(n^2) O(n2),在进行测试的时候回出现INT溢出,因此在求和的过程中要用long long int
/**
* 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:
int ans = 0;
void dfs(TreeNode* root,long long int now_val,int targetSum){
if(!root)return;
now_val += root->val;
if(now_val == targetSum){
ans++;
}
dfs(root->left,now_val,targetSum);
dfs(root->right,now_val,targetSum);
return;
}
void start(TreeNode* root,int targetSum){
if(!root)return;
dfs(root,0,targetSum);
start(root->left,targetSum);
start(root->right,targetSum);
return;
}
int pathSum(TreeNode* root, int targetSum) {
start(root,targetSum);
return ans;
}
};
2.前缀和
在这个题目中可以使用前缀和的方法,先序遍历每个节点,记录从根节点到该节点的累计和,以map存储,同时判断该节点的累积和-targetSum的值是否在map中,若存在几个则将路径数加几,否则,将该累计和从map中删除。
/**
* 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:
unordered_map<long long int, int>mp;
int ans = 0;
void dfs(TreeNode* root,long long int now_val,int targetSum){
if(!root)return;
now_val += root->val;
if(mp.count(now_val-targetSum)){
ans += mp[now_val-targetSum];
}
mp[now_val] += 1;
dfs(root->left,now_val,targetSum);
dfs(root->right,now_val,targetSum);
mp[now_val] -= 1;
return;
}
int pathSum(TreeNode* root, int targetSum) {
mp[0] = 1;
dfs(root,0,targetSum);
return ans;
}
};