面试题 04.12. Paths with Sum LCCI
/**
* 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:
void DFS(TreeNode* root, int sum, int now_sum, int &cnt) {
if(!root) return ;
now_sum += root->val;
if(now_sum == sum) cnt++;
if(root->left) DFS(root->left, sum, now_sum, cnt);
if(root->right) DFS(root->right, sum, now_sum, cnt);
}
int pathSum(TreeNode* root, int sum) {
if(!root) return 0;
int cnt = 0;
DFS(root, sum, 0, cnt);
return cnt + pathSum(root->left, sum) + pathSum(root->right, sum);
}
};