Given a binary tree withnnodes, your task is to check if it's possible to partition the tree to two trees which have the equal sum of values after removing exactly one edge on the original tree.
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.
Note
按edge划分子树
找sum/2的子树和就行!
Code
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicbooleancheckEqualTree(TreeNode root) {if (root ==null) {returnfalse; }int total =sum(root);boolean[] res =newboolean[1];sum(root.left, total, res);sum(root.right, total, res);return res[0]; }privateintsum(TreeNode root) {if (root ==null) {return0; }returnroot.val+sum(root.left)+sum(root.right); }privateintsum(TreeNode root,int total,boolean[] res) {if (root ==null) {return0; }int sum =root.val+sum(root.left, total, res)+sum(root.right, total, res);if (sum *2== total) { res[0] =true; }return sum; }}