Equal Tree Partition Problem
Description
LeetCode Problem 663.
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:

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

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
Approach: Subtree Sums
Removing one edge cuts off one subtree: the subtree of the child end of that edge. The two parts then have sums s and total - s, where s is that subtree's sum. They are equal exactly when s == total / 2.
So compute every subtree sum in one postorder traversal and save them in a list. The answer is true when total is even and some subtree sum equals total / 2.
The tricky case is the whole tree itself. Its sum is total, and it is not a subtree we can cut off, because there is no edge above the root. Usually this does not matter, but when total is 0 the root's own sum would match total / 2 = 0. For [0,-1,1], the answer is false: cutting off either child leaves -1 against 1. In postorder the root's sum is saved last, so we remove the last entry before searching.
Complexity: O(n) time and O(n) extra space for the list of sums and the recursion.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def checkEqualTree(self, root: Optional[TreeNode]) -> bool:
sums = [] # the sum of every subtree, in postorder
def subtree_sum(node):
if node is None:
return 0
s = node.val + subtree_sum(node.left) + subtree_sum(node.right)
sums.append(s)
return s
total = subtree_sum(root)
sums.pop() # the whole tree comes last; it is not a subtree we can cut off
return total % 2 == 0 and total // 2 in sums