Equal Tree Partition - 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.
A partition means dividing the tree into two separate connected components. When you remove an edge, you get two subtrees - the removed subtree and the remaining tree. Both must have the same sum of node values.
Note: You cannot remove the edge above the root node (since there isn't one).
Input & Output
Example 1 — Valid Partition
$
Input:
root = [5,10,10,null,null,2,3]
›
Output:
true
💡 Note:
Original tree sum = 5+10+10+2+3 = 30. We can remove the edge above the right subtree (10,2,3) which has sum 15, leaving the left part (5,10) with sum 15. Both parts have equal sum 15.
Example 2 — No Valid Partition
$
Input:
root = [1,2,10,null,null,2,20]
›
Output:
false
💡 Note:
Original tree sum = 1+2+10+2+20 = 35. Since 35 is odd, we cannot split it into two equal parts. Any partition would result in unequal sums.
Example 3 — Single Split Works
$
Input:
root = [2,1,1]
›
Output:
true
💡 Note:
Tree sum = 2+1+1 = 4. We can remove edge to left child (value 1), creating partitions with sums 1 and 3. Wait, that's not equal. Actually, removing edge to right child gives us partition sums 1 and 3. This should be false, but let me recalculate: we need sum 2 on each side. Remove left subtree (sum 1) leaves right side with sum 3. This doesn't work.
Constraints
- The number of nodes in the tree is in the range [1, 104].
- -105 ≤ Node.val ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with node values [5,10,10,null,null,2,3]
2
Find Target
Calculate total sum (30) and target sum (15)
3
Check Partition
Find subtree with sum 15, remove its parent edge
Key Takeaway
🎯 Key Insight: A tree can be equally partitioned if any subtree has exactly half the total sum
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code