题目
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11分析
在二叉树中找到和为给定数字的路径个数,路径可以不必从根节点到叶节点,但必须是向下方向的,输出总的路径个数,这道题跟从根节点到叶节点路径和相似,也是需要保存之前计算的路径和,并与给定的sum比较,一种方法是用vector保存所有可能路径传递给子树,即如果当前节点加入到父节点构成的路径中,则对vector中元素与当前值相加并判断,如果当前节点不加入,则对当前节点判断并加入vector当做新的路径起点,另外一种更高效的方法是记录到达当前节点的所有路径和及其出现次数,并且查看减去sum后的值是否出现在记录中,如果出现,说明在当前节点的路径中,有一部分的和构成了sum,故出现次数就是减去sum的值出现次数,因为代表了一共有这么多的前缀路径。
方法一:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void comPathSum(TreeNode* root,int sum,vector<int> parentSum,int& res){//利用向量parentSum记录从父节点向下传递的和
for(int i=0;i<parentSum.size();++i){//对于当前节点有两种选择,第一对父节点传递的值累加,第二从自己开始计算,for循环计算累加过程有多少符合要求的
parentSum[i]+=root->val;
if(parentSum[i]==sum)
++res;
}
parentSum.push_back(root->val);//还有从自身开始计算的
if(root->val==sum)
++res;
if(root->left!=NULL)//递归调用左右子树
comPathSum(root->left,sum,parentSum,res);
if(root->right!=NULL)
comPathSum(root->right,sum,parentSum,res);
}
int pathSum(TreeNode* root, int sum) {
vector<int> parentSum;
if(root==NULL)
return 0;
int res=0;
comPathSum(root,sum,parentSum,res);
return res;
}
};
方法二:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> mSum;
mSum[0]++;
int total = 0;
helper(root, 0, sum, total, mSum);//利用mSum保存所有之前经过的路径和
return total;
}
void helper(TreeNode *p, int cur, int sum, int &total, unordered_map<int, int> &mSum) {
if (!p) return;
cur += p->val;//先对当前节点进行累加
if (mSum.find(cur - sum) != mSum.end()) //不在mSum中寻找sum,而是cur-sum,即前缀和,如果找到了,说明加上当前节点的路径和-sum的结果是之前路径中到某个节点的和,即可以寻找到一个和为sum的路径,而这样的路径个数记录在mSum中,因此更新路径个数结果
total += mSum[cur - sum];
mSum[cur]++;//对当前路径和在mSum中出现的次数进行更新,然后遍历左右子树
helper(p->left, cur, sum, total, mSum);
helper(p->right, cur, sum, total, mSum);
mSum[cur]--;//递归结束后对当前和的个数减少,因为向上传递后无法再到达当前节点
}
};
参考文章:
C++ solution with prefix sum stored in hash table