This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 pathSum(TreeNode* root, int sum) { | |
unordered_map<int, int> map; | |
map[0] = 1; | |
int res = 0; | |
maxPath(root, 0, sum, res, map); | |
return res; | |
} | |
private: | |
void maxPath(TreeNode* root, int preSum, int sum, int& count, unordered_map<int, int>& preSums) | |
{ | |
if(!root)return; | |
preSum += root->val; | |
count += preSums[preSum - sum]; | |
++preSums[preSum]; | |
maxPath(root->left, preSum, sum, count, preSums); | |
maxPath(root->right, preSum, sum, count, preSums); | |
--preSums[preSum]; | |
} | |
}; |
No comments:
Post a Comment