663. Equal Tree Partition

663. Equal Tree Partition

Description

Given the root of a binary tree, return true if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree.

Example 1:

1
2
Input: root = [5,10,10,null,null,2,3]
Output: true

Example 2:

1
2
3
Input: root = [1,2,10,null,null,2,20]
Output: false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • -10^5 <= Node.val <= 10^5

Hints/Notes

  • N/A

Solution

Language: C++

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
unordered_set<int> s;

bool checkEqualTree(TreeNode* root) {
int treeSum = root->val + traverse(root->left) + traverse(root->right);
if (treeSum % 2) {
return false;
}
return s.contains(treeSum / 2);
}

int traverse(TreeNode* root) {
if (!root) {
return 0;
}
int val = root->val;

int left = traverse(root->left);
int right = traverse(root->right);

val += left + right;

s.insert(val);
return val;
}
};