[LeetCode] Equal Tree Partition 划分等价树

Given a binary tree with `n` nodes, your task is to check if it’s possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree.

Example 1:

```Input:
5
/ \
10 10
/  \
2   3

Output: True
Explanation:
5
/
10

Sum: 15

10
/  \
2    3

Sum: 15
```

Example 2:

```Input:
1
/ \
2  10
/  \
2   20

Output: False
Explanation: You can't split the tree into two trees with equal sum after removing exactly one edge on the tree.```

```class Solution {
public:
bool checkEqualTree(TreeNode* root) {
unordered_map<int, int> m;
int sum = helper(root, m);
if (sum == 0) return m[0] > 1;
return sum % 2 == 0 && m.count(sum / 2);
}
int helper(TreeNode* node, unordered_map<int, int>& m) {
if (!node) return 0;
int cur = node->val + helper(node->left, m) + helper(node->right, m);
++m[cur];
return cur;
}
};```

https://discuss.leetcode.com/topic/100179/java-c-simple-solution-with-only-one-hashmap

原文作者：Grandyang
原文地址: http://www.cnblogs.com/grandyang/p/7550360.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。