- count函数: root为根节点,且为路径起点,其子路径中所有和为sum的路径个数
- pathSum: root为根节点,其子路径中所有和为sum的路径个数
/**
* 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 sum) {
if(root == nullptr) return 0;
return count(root, sum) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
int count(TreeNode* root, int sum){
if(root == nullptr) return 0;
return (root->val == sum) + count(root->left, sum-root->val) + count(root->right, sum - root->val);
}
};