> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0663-equal-tree-partition.md).

# 0663. Equal Tree Partition

<https://leetcode.com/problems/equal-tree-partition>

## Description

Given the `root` of a binary tree, return `true` *if you can partition the tree into two trees with equal sums of values after removing exactly one edge on the original tree*.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/05/03/split1-tree.jpg)

```
**Input:** root = [5,10,10,null,null,2,3]
**Output:** true
```

**Example 2:**

![](https://assets.leetcode.com/uploads/2021/05/03/split2-tree.jpg)

```
**Input:** root = [1,2,10,null,null,2,20]
**Output:** false
**Explanation:** You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.
```

**Constraints:**

* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`

## ac

```java
/**
 * 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 || root.left == null && root.right == null) return false;
        Set<Integer> vals = new HashSet<>();
        int sum = root.val + sum(root.left, vals) + sum(root.right, vals); // don't count root, because, root is not a substree
        if (sum % 2 != 0) return false;

        return vals.contains(sum/2);
    }

    public int sum(TreeNode node, Set<Integer> vals) {
        if (node == null) return 0;
        int left = sum(node.left,vals);
        int right = sum(node.right, vals);
        int res = node.val + left + right;
        vals.add(res);
        return res;
    }
}

/*
1) sum up all value; 2) if meet 1/2 sum, return true; 3) careful:  don't count root, because, root is not a substree
*/
```
