-
Notifications
You must be signed in to change notification settings - Fork 0
/
437.hpp
45 lines (35 loc) · 817 Bytes
/
437.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// Created by bai on 17-6-28.
//
#ifndef LEETCODE_437_HPP
#define LEETCODE_437_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include "../common/leetcode.hpp"
using namespace std;
class Solution {
public:
int pathSum(TreeNode *root, int sum) {
psums.clear();
psums[0]++;
return pathSumR(root, sum, 0);
}
private:
unordered_map<int, int> psums;
int pathSumR(TreeNode *node, int sum, int ps) {
if (node == nullptr) {
return 0;
}
ps += node->val;
int cnt = psums[ps - sum];
psums[ps]++;
cnt += pathSumR(node->left, sum, ps);
cnt += pathSumR(node->right, sum, ps);
psums[ps]--;
return cnt;
}
};
#endif //LEETCODE_437_HPP