Equal Tree Partition
Example
Input:
5
/ \
10 10
/ \
2 3
Output: True
Explanation:
5
/
10
Sum: 15
10
/ \
2 3
Sum: 15Note
Code
Last updated
Input:
5
/ \
10 10
/ \
2 3
Output: True
Explanation:
5
/
10
Sum: 15
10
/ \
2 3
Sum: 15Last updated
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./**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean checkEqualTree(TreeNode root) {
if (root == null) {
return false;
}
int total = sum(root);
boolean[] res = new boolean[1];
sum(root.left, total, res);
sum(root.right, total, res);
return res[0];
}
private int sum(TreeNode root) {
if (root == null) {
return 0;
}
return root.val + sum(root.left) + sum(root.right);
}
private int sum(TreeNode root, int total, boolean[] res) {
if (root == null) {
return 0;
}
int sum = root.val + sum(root.left, total, res) + sum(root.right, total, res);
if (sum * 2 == total) {
res[0] = true;
}
return sum;
}
}