> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Equal Tree Partition Python Solution

> Tested Python solution for LeetCode 663 with 26 pytest cases. Generate a practice environment with lcpy.

LeetCode 663, [Medium](/catalog/medium). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/equal-tree-partition/description/).

Generate this problem as a practice environment: tested reference solution, 26 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 663   # by problem number
lcpy gen -s equal_tree_partition   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/split1-tree.jpg)

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

![Example 2](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/0600-0699/0663.Equal%20Tree%20Partition/images/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, 10^4].
-10^5 \<= Node.val \<= 10^5

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/equal_tree_partition/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/equal_tree_partition/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(n)
    def check_equal_tree(self, root: TreeNode[int] | None) -> bool:
        if root is None:
            return False
        # Iterative postorder: cutting the edge above `node` leaves a piece whose
        # sum is that node's subtree sum, so every non-root node is a candidate.
        # TreeNode is unhashable, so sums are keyed by identity instead of node.
        sums: dict[int, int] = {}
        order: list[TreeNode[int]] = []
        stack: list[tuple[TreeNode[int] | None, bool]] = [(root, False)]
        while stack:
            node, expanded = stack.pop()
            if node is None:
                continue
            if not expanded:
                stack.append((node, True))
                stack.append((node.left, False))
                stack.append((node.right, False))
                continue
            left = sums[id(node.left)] if node.left is not None else 0
            right = sums[id(node.right)] if node.right is not None else 0
            sums[id(node)] = left + right + node.val
            order.append(node)
        total = sums[id(root)]
        if total % 2 != 0:
            return False
        half = total // 2
        return any(sums[id(node)] == half for node in order[:-1])
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.