864. 相等树划分
给定一个有
n
个节点的二叉树,请问可否在去掉
恰好一条边
的情况下,将原有的树分成两个节点值总和相等的两个树。
样例
样例 1:
输入: {5,10,10,#,#,2,3}
输出: true
解释:
原始的树:
5
/ \
10 10
/ \
2 3
两棵子树:
5 10
/ / \
10 2 3
样例 2:
输入: {1,2,10,#,#,2,20}
输出: false
解释:
原始的树:
1
/ \
2 10
/ \
2 20
说明
注意事项
-
树的节点的值在 [-100000, 100000] 范围内。
-
1 <= n <= 10000
-
保证树不为 null
/**
* 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 checkEqualTree(TreeNode root) {
int left = helper(root.left);
int right = helper(root.right);
if (right - left == root.val || left - right == root.val) {
return true;
} else {
root.val = (root.val+right + left)/2;
return checkEqualTree(root.left, root.val) || checkEqualTree(root.right, root.val);
}
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
root.val = root.val + helper(root.left) + helper(root.right);
return root.val;
}
private boolean checkEqualTree(TreeNode root, int lastValue) {
if (root == null) {
return false;
}
if (root.val < lastValue) {
return false;
}
if (root.val == lastValue) {
return true;
}
return checkEqualTree(root.left, lastValue) || checkEqualTree(root.right, lastValue);
}
}
/**
* 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 checkEqualTree(TreeNode root) {
int left = helper(root.left);
int right = helper(root.right);
if (right - left == root.val || left - right == root.val) {
return true;
} else {
return checkEqualTree(root.left, root.val + right) || checkEqualTree(root.right, root.val + left);
}
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
root.val = root.val + helper(root.left) + helper(root.right);
return root.val;
}
private boolean checkEqualTree(TreeNode root, int lastValue) {
if (root == null) {
return false;
}
if (root.val < lastValue) {
return false;
}
boolean result = false;
if (root.right != null) {
if (root.right.val + root.right.val == root.val + lastValue) {
return true;
}
result = checkEqualTree(root.right, root.val - root.right.val + lastValue);
}
if (root.left != null) {
if (root.left.val + root.left.val == root.val + lastValue) {
return true;
}
result |= checkEqualTree(root.left, root.val - root.left.val + lastValue);
}
return result;
}
}