|
| 1 | +/* |
| 2 | +Equal Tree Partition |
| 3 | +==================== |
| 4 | +
|
| 5 | +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. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: root = [5,10,10,null,null,2,3] |
| 9 | +Output: true |
| 10 | +
|
| 11 | +Example 2: |
| 12 | +Input: root = [1,2,10,null,null,2,20] |
| 13 | +Output: false |
| 14 | +Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree. |
| 15 | +
|
| 16 | +Constraints: |
| 17 | +The number of nodes in the tree is in the range [1, 104]. |
| 18 | +-105 <= Node.val <= 105 |
| 19 | +*/ |
| 20 | + |
| 21 | +/** |
| 22 | + * Definition for a binary tree node. |
| 23 | + * struct TreeNode { |
| 24 | + * int val; |
| 25 | + * TreeNode *left; |
| 26 | + * TreeNode *right; |
| 27 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 28 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 29 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 30 | + * }; |
| 31 | + */ |
| 32 | + |
| 33 | +class Solution { |
| 34 | +public: |
| 35 | + int dfs1(TreeNode* root) { |
| 36 | + if(!root) return 0; |
| 37 | + return root->val + dfs1(root->left) + dfs1(root->right); |
| 38 | + } |
| 39 | + |
| 40 | + int dfs2(TreeNode* root, int& halfSum, bool& ans) { |
| 41 | + int left = 0, right = 0; |
| 42 | + if(root->left) { |
| 43 | + left = dfs2(root->left, halfSum, ans); |
| 44 | + if(left == halfSum) { |
| 45 | + ans = true; |
| 46 | + return 0; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if(root->right) { |
| 51 | + right = dfs2(root->right, halfSum, ans); |
| 52 | + if(right == halfSum) { |
| 53 | + ans = true; |
| 54 | + return 0; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return root->val + left + right; |
| 59 | + } |
| 60 | + |
| 61 | + bool checkEqualTree(TreeNode* root) { |
| 62 | + int fullSum = dfs1(root); |
| 63 | + |
| 64 | + if(fullSum % 2 != 0) return false; |
| 65 | + int halfSum = fullSum / 2; |
| 66 | + |
| 67 | + bool ans = false; |
| 68 | + dfs2(root, halfSum, ans); |
| 69 | + |
| 70 | + return ans; |
| 71 | + } |
| 72 | +}; |
0 commit comments