根据递归定义:
int pathSum(root, target) 表示从当前根节点root出发,值等于target的所有路径个数
它可以分成三类,第一类是从root->left出发,第二类是从root->right出发,第三类是从包含当前root的路径。
因此不难写出下面代码
/**
* 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 pathSum(TreeNode* root, int targetSum) {
if(root == nullptr){
return 0;
}
return pathSumFromRoot(root, targetSum) + pathSum(root->left, targetSum) + pathSum(root->right, targetSum);
}
int pathSumFromRoot(TreeNode* root, int targetSum){
if(root == nullptr){
return 0;
}
return (root->val == targetSum ? 1 : 0) + pathSumFromRoot(root->left, targetSum - root->val) + pathSumFromRoot(root->right, targetSum - root->val);
}
};
优化方案采用前缀和的优化,将从根节点到任意节点的前缀和记录下来,然后两段前缀和的差,即是路径答案,遍历的时候采用前序遍历递归回溯,这样能保证这样的答案一定正确的。
/**
* 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 cur = 0;
int pathSum(TreeNode* root, int targetSum) {
cnt[0] = 1;
dfs(root, 0, targetSum);
return res;
}
void dfs(TreeNode* root, int cur, int targetSum){
if(root == nullptr){
return;
}
cur += root->val;
res += cnt[cur - targetSum];
cnt[cur]++;
dfs(root->left, cur, targetSum);
dfs(root->right, cur, targetSum);
cnt[cur]--;
}
};