1,题目要求
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.
您将获得一个二叉树,其中每个节点都包含一个整数值。
找到与给定值相加的路径数。
路径不需要在根或叶子处开始或结束,但必须向下(仅从父节点行进到子节点)。
该树的节点数不超过1,000个,值范围为-1,000,000到1,000,000。
2,题目思路
这道题,是求一条路径的和等于给定值的路径的数目。
需要注意的,这里的一条路径,只能是从上到下的,但是,不一定要从根节点到叶节点,可以是一部分。
因为有事关于树的遍历,因此,使用递归会比较合适。
该问题的一个特点,就是使用两个递归方案:
- 其中一个递归,是额外定义的Helper函数,用来计算从特定顶点开始的树中是否存在和等于sum的路径。这里,递归的过程中,用到了与之间Two Sum类似的策略——即相减以得可取值的办法。
- 另外一个递归,则是递归的遍历树中的每一个节点。
3,代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if(root == nullptr)
return 0;
return pathSumHelper(root, sum) +
pathSum(root->left, sum) +
pathSum(root->right,sum);
}
private:
//计算从对应顶点开始的树中是否存在和等于sum的路径
int pathSumHelper(TreeNode* node, int sum){
if(node == nullptr)
return 0;
return (node->val == sum? 1 : 0) +
pathSumHelper(node->left, sum - node->val) +
pathSumHelper(node->right,sum - node->val);
}
};