forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathequal-tree-partition.cpp
More file actions
35 lines (33 loc) · 860 Bytes
/
equal-tree-partition.cpp
File metadata and controls
35 lines (33 loc) · 860 Bytes
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
// Time: O(n)
// Space: O(n)
/**
* 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:
bool checkEqualTree(TreeNode* root) {
unordered_map<int, int> lookup;
auto total = getSumHelper(root, &lookup);
if (total == 0) {
return lookup[total] > 1;
}
return total % 2 == 0 && lookup.count(total / 2);
}
private:
int getSumHelper(TreeNode* node, unordered_map<int, int> *lookup) {
if (!node) {
return 0;
}
int total = node->val +
getSumHelper(node->left, lookup) +
getSumHelper(node->right, lookup);
++(*lookup)[total];
return total;
}
};