*Leetcode 437. 路径总和 III
Posted Z-Pilgrim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*Leetcode 437. 路径总和 III相关的知识,希望对你有一定的参考价值。
https://leetcode.cn/problems/path-sum-iii/
树上前缀和
class Solution
public:
void dfs(unordered_map<long long, int> &hash, TreeNode*root, long long cur, long long tar, int &ans)
if(!root) return;
cur += root->val;
if(hash.find(cur - tar ) != hash.end())
ans += hash[cur - tar];
hash[cur] ++;
dfs(hash, root->left, cur, tar, ans);
dfs(hash, root->right, cur, tar, ans);
hash[cur] --;
int pathSum(TreeNode* root, int targetSum)
unordered_map<long long, int> hash;
hash[0] =1;
int ans = 0;
dfs(hash, root, 0, targetSum, ans);
return ans;
;
暴力
class Solution
public:
void dfs(TreeNode* root, long long cur, long long target, int &ans)
if(!root)
return;
if(cur + root->val == target)
ans ++;
;
dfs(root->left, cur + root->val, target, ans);
dfs(root->right, cur + root->val, target, ans);
void dfs(TreeNode* root, long long target, int &ans)
if(!root) return;
dfs(root, 0, target, ans);
dfs(root->left, target, ans);
dfs(root->right, target, ans);
int pathSum(TreeNode* root, int targetSum)
// dp[i] =p
int ans = 0;
dfs(root, targetSum, ans);
return ans;
;
以上是关于*Leetcode 437. 路径总和 III的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 437. 路径总和 III ☆☆☆(递归)