https://leetcode.com/problems/path-sum-iii/
本题和之前的Path 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:
//以Node为根节点的二叉树中,寻找包含Node 的路径
int findPath(TreeNode* node ,int num){
if( node == nullptr )
return 0;
int res = 0;
if( node->val == num )
res += 1;
res += findPath( node->left, num - node->val );
res += findPath( node->right, num - node->val );
return res;
}
int pathSum(TreeNode* root, int sum) {
if( root == nullptr )
return 0;
int res = findPath( root,sum );
res += pathSum( root->left, sum );
res += pathSum( root->right, sum );
return res;
}
};