Description:
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.
对于这个题目,我们可以考虑用dp算法来考虑是否要将当前节点作为路径中的一个节点。对于取和不取当前节点,都要再对当前节点的左右儿子递归考察。但是,由于和是连续的,所以我们要用一个变量来记录是否可以跳过当前节点。总之,这道题就是一个简单的递归问题。
/**
* 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) {
return path(root, sum, true);
}
int path(TreeNode* root, int sum, bool flag) {
if (!root) return 0;
int here = 0;
if (root->val == sum) {
here = 1;
}
int left1=0, left2=0, right1=0, right2=0;
if (root->left) {
left1 = path(root->left, sum - root->val, false);
if (flag) left2 = path(root->left, sum, true);
}
if (root->right) {
right1 = path(root->right, sum - root->val, false);
if (flag) right2 = path(root->right, sum, true);
}
return here + left1 + left2 + right1 + right2;
}
};