# 663. Equal Tree Partition 均匀树划分

@TOC

## # 题目描述

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.
``````

Note:

1. The range of tree node value is in the range of [-100000, 100000].
2. 1 <= n <= 10000

## # 解题方法

### # 递归

C++代码如下：

``````/**
* 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) {
int total = getSum(root);
if (total & 1)
return false;
int half = total / 2;
return subEqual(root->left, half) || subEqual(root->right, half);
}
bool subEqual(TreeNode* root, int target) {
if (!root) return false;
if (getSum(root) == target)
return true;
return subEqual(root->left, target) || subEqual(root->right, target);
}
int getSum(TreeNode* root) {
if (!root) return 0;
if (m.count(root))
return m[root];
int res = root->val + getSum(root->left) + getSum(root->right);
m[root] = res;
return res;
}
private:
unordered_map<TreeNode*, int> m;
};
``````

## # 日期

2019 年 9 月 21 日 —— 莫生气，我若气病谁如意