题目:
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:
解答:
/**
* 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) {//每个节点维护一个数组,里面的值是以该节点作为最后一个node,可能的和
vector<int> maySum;
return preOrder(root,maySum,sum);
}
int preOrder(TreeNode* T,vector<int> maySum,int sum){
if(T == NULL)
return 0;
int result;
int value = T->val;
if(value == sum)
++result;
int len = maySum.size();
for(int i=0;i<len;++i){
maySum[i] += value;
if(maySum[i] == sum)
++result;
}
maySum.push_back(value);
int leftResult = preOrder(T->left, maySum,sum);
int rightResult = preOrder(T->right,maySum,sum);
result += leftResult + rightResult;
return result;
// return result + preOrder(T->left, maySum,sum) + preOrder(T->right,maySum,sum);//这样写超时
}
};