Leetcode #663: Equal Tree Partition
In this guide, we solve Leetcode #663 Equal Tree Partition in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Tree, Depth-First Search, Binary Tree
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: root = [5,10,10,null,null,2,3]
Output: true
Python Solution
# 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: TreeNode) -> bool:
def sum(root):
if root is None:
return 0
l, r = sum(root.left), sum(root.right)
seen.append(l + r + root.val)
return seen[-1]
seen = []
s = sum(root)
if s % 2 == 1:
return False
seen.pop()
return s // 2 in seen
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.