题目:
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:
- The range of tree node value is in the range of [-100000, 100000].
- 1 <= n <= 10000
思路:
我们建立一个哈希表,记录每个节点对应的子树的和,然后遍历树中的每一个子节点,一旦发现该子节点的和为整个树的和的一半,就说明找到了一个符合条件的split,从这里切分,可以将整个树划分成为和相等的两棵树。
代码:
/**
* 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<TreeNode*, int> hash; // node -> sum
int sum = getSum(root, hash);
if (sum % 2 != 0) {
return false;
}
return canSplit(root, hash, sum / 2);
}
private:
bool canSplit(TreeNode* root, unordered_map<TreeNode*, int> &hash, int half_sum) {
if (root == NULL) {
return false;
}
if (root->left && hash[root->left] == half_sum) {
return true;
}
if (root->right && hash[root->right] == half_sum) {
return true;
}
return canSplit(root->left, hash, half_sum) || canSplit(root->right, hash, half_sum);
}
int getSum(TreeNode* root, unordered_map<TreeNode*, int> &hash) {
if (root == NULL) {
return 0;
}
int left = getSum(root->left, hash);
int right = getSum(root->right, hash);
int sum = left + right + root->val;
hash[root] = sum;
return sum;
}
};