Equal Tree Partition 07/27
Last updated
Last updated
Given
1
/ \
2 10
/ \
2 20
return False
Explanation:
You can't split the tree into two trees with equal sum after removing exactly one edge on the tree./**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode
* @return: return a boolean
*/
public boolean equal = false;
public boolean checkEqualTree(TreeNode root) {
// write your code here
int topVal = helper(root);
if(topVal %2 == 0){
return check(root.left,topVal/2) || check(root.right, topVal/2);
}
return false;
}
public boolean check(TreeNode root,int target){
if(root == null){
return false;
}
if(target == root.val){
return true;
}
return check(root.left,target) || check(root.right,target);
}
public int helper(TreeNode root){
if(root == null){
return 0;
}
int leftSum = helper(root.left);
int rightSum = helper(root.right);
root.val = root.val+leftSum+rightSum;
return root.val;
}
}