找遍所有路径,特判以根为起点的串即可。
代码:
/** * 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 ans = 0; map <int, int> m; int pathSum(TreeNode* root, int sum) { findSum(root, sum, 0); return ans; } void findSum(TreeNode *node, int sum, int num){ if(node == NULL) return; num += node->val; if(num == sum) ans += m[0]+1; else ans += m[num-sum]; m[num]++; findSum(node->left, sum, num); findSum(node->right, sum, num); m[num]--; } };