BiruLyu
9/7/2017 - 1:15 AM

663. Equal Tree Partition.java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int dfs(Set<Integer> subTreeSum, TreeNode root) {
        if (root == null) return 0;
        if (root.left == null && root.right == null) {
            subTreeSum.add(root.val);
            return root.val;
        }
        int left = dfs(subTreeSum, root.left);
        subTreeSum.add(left);
        int right = dfs(subTreeSum, root.right);
        subTreeSum.add(right);
        return left + right + root.val;
    }
    public boolean checkEqualTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) return false;
        Set<Integer> subTreeSum = new HashSet<>();
        int total = dfs(subTreeSum, root);
        if (total % 2 != 0) return false;
        return subTreeSum.contains(total/2);
    }
}