Equal Tree Partition - Problem
Imagine you have a binary tree where each node contains a numerical value. Your task is to determine if you can split this tree into two separate trees by removing exactly one edge, such that both resulting trees have equal sum of node values.
Think of it like dividing a family tree into two branches where both sides have equal "wealth" (sum of values). You need to find the perfect cut point!
Goal: Return true if such a partition exists, false otherwise.
Example: If you have a tree with total sum 10, you need to find an edge that when removed, creates one subtree with sum 5 and another with sum 5.
Input & Output
example_1.py โ Basic Equal Partition
$
Input:
root = [5,10,10,null,null,2,3]
โบ
Output:
true
๐ก Note:
We can remove the edge between node 5 and node 10 (right child). This creates two trees: one with sum 15 (containing 5 and left subtree 10) and another with sum 15 (containing right subtree with 10,2,3). Both sums are equal.
example_2.py โ Impossible Partition
$
Input:
root = [1,2,10,null,null,2,20]
โบ
Output:
false
๐ก Note:
Total sum is 35, which is odd. Since we need two equal parts, and 35 cannot be divided evenly into two integers, no equal partition exists.
example_3.py โ Single Node
$
Input:
root = [0]
โบ
Output:
false
๐ก Note:
A single node tree has no edges to remove, so no partition is possible.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 โค Node.val โค 105
- Note: Removing an edge splits the tree into exactly two components
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Total Weight
Sum all node values to get the total tree weight
2
Find Half-Weight Subtree
Look for a subtree with exactly half the total weight
3
Validate Cut Point
Ensure the subtree isn't the entire tree (can't cut above root)
Key Takeaway
๐ฏ Key Insight: If any subtree has sum = total_sum/2, removing the edge to its parent creates two trees with equal sums!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code