forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEqual Tree Partition.cpp
72 lines (59 loc) · 1.84 KB
/
Equal Tree Partition.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Equal Tree Partition
====================
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:
Input: root = [5,10,10,null,null,2,3]
Output: true
Example 2:
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, 104].
-105 <= Node.val <= 105
*/
/**
* 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:
int dfs1(TreeNode* root) {
if(!root) return 0;
return root->val + dfs1(root->left) + dfs1(root->right);
}
int dfs2(TreeNode* root, int& halfSum, bool& ans) {
int left = 0, right = 0;
if(root->left) {
left = dfs2(root->left, halfSum, ans);
if(left == halfSum) {
ans = true;
return 0;
}
}
if(root->right) {
right = dfs2(root->right, halfSum, ans);
if(right == halfSum) {
ans = true;
return 0;
}
}
return root->val + left + right;
}
bool checkEqualTree(TreeNode* root) {
int fullSum = dfs1(root);
if(fullSum % 2 != 0) return false;
int halfSum = fullSum / 2;
bool ans = false;
dfs2(root, halfSum, ans);
return ans;
}
};