forked from zhuli19901106/leetcode-zhuli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-tilt_1_AC.cpp
47 lines (43 loc) · 1.09 KB
/
binary-tree-tilt_1_AC.cpp
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
46
47
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <cmath>
#include <unordered_map>
using std::abs;
using std::unordered_map;
class Solution {
public:
Solution() {
tilt[NULL] = 0;
sum[NULL] = 0;
tiltSum[NULL] = 0;
}
int findTilt(TreeNode *root) {
if (tiltSum.find(root) == tiltSum.end()) {
int sl = findSum(root->left);
int sr = findSum(root->right);
tilt[root] = abs(sl - sr);
tiltSum[root] = tilt[root] + findTilt(root->left) + findTilt(root->right);
}
return tiltSum[root];
}
~Solution() {
tilt.clear();
sum.clear();
tiltSum.clear();
}
private:
unordered_map<TreeNode *, int> tilt, sum, tiltSum;
int findSum(TreeNode *root) {
if (sum.find(root) == sum.end()) {
sum[root] = root->val + findSum(root->left) + findSum(root->right);
}
return sum[root];
}
};