112. 路径总和
思路: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 {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return targetSum == root->val;
return hasPathSum(root->left, targetSum-root->val) || hasPathSum(root->right, targetSum-root->val);
}
};
113. 路径总和 II
思路:dfs
记得还原path
/**
* 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:
vector<vector<int>> ans;
vector<int> path;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if (root) dfs(root, sum);
return ans;
}
void dfs(TreeNode* root, int sum) {
path.push_back(root->val);
sum -= root->val;
if (!root->left && !root->right) {
if (sum == 0) ans.push_back(path);
}
else {
if (root->left) dfs(root->left, sum);
if (root->right) dfs(root->right, sum);
}
path.pop_back();
}
};
437. 路径总和 III
思路三:前缀和
维护根节点到当前节点前缀和的次数,答案+cnt[cur−sum]cnt[cur-sum]cnt[cur−sum]
/**
* 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<int, int> cnt;
int res = 0;
int pathSum(TreeNode* root, int sum) {
cnt[0] ++ ;
dfs(root, sum, 0);
return res;
}
void dfs(TreeNode* root, int sum, int cur) {
if (!root) return ;
cur += root->val;
res += cnt[cur - sum];
cnt[cur] ++ ;
dfs(root->left, sum, cur), dfs(root->right, sum, cur);
cnt[cur] -- ;
}
};
1330



被折叠的 条评论
为什么被折叠?



