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
Equal Tree Partition Visualization10CUT HERE!5102346Left Side10 + 5 + 2 + 3 = 20Sum: 20Right Side10 + 4 + 6 = 20Sum: 20โœ“ EQUAL PARTITION FOUND!Total Sum: 40 โ†’ Target: 20 โ†’ Found subtree with sum 20 โœ“
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!
Asked in
Google 25 Amazon 18 Microsoft 12 Meta 8
28.1K Views
Medium Frequency
~18 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen