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: false
💡 Note: Tree sum = 2+1+1 = 4. Target sum for each partition would be 2. However, the left subtree has sum 1 and the right subtree has sum 1. Neither subtree has the required sum of 2, so no valid partition exists.

Constraints

  • The number of nodes in the tree is in the range [1, 104].
  • -105 ≤ Node.val ≤ 105

Visualization

Tap to expand
Equal Tree Partition INPUT Binary Tree Structure 5 10 10 2 3 Array Representation: [5,10,10,null,null,2,3] Total Sum = 30 Target = 30/2 = 15 ALGORITHM STEPS 1 Calculate Total Sum DFS to get sum = 30 2 Check if Sum is Even 30 % 2 == 0 [OK] 3 Store Subtree Sums Memoize each subtree sum 4 Find Target Subtree Check if sum=15 exists Subtree Sums (Memo) Node 5: 30 (root) Node 10: 10 (left) Node 10: 15 (right) Node 2: 2 Node 3: 3 FOUND! FINAL RESULT Valid Partition Found Tree 1 (Sum=15) 5 10 CUT Tree 2 (Sum=15) 10 2 3 Output: true Key Insight: If total sum is S, we need to find a subtree with sum = S/2. When we remove the edge connecting this subtree, both parts will have equal sums. Use DFS to compute all subtree sums and store them. Check if S/2 exists in the stored sums (excluding root). TutorialsPoint - Equal Tree Partition | DFS with Memoization
Asked in
Facebook 25 Amazon 15 Microsoft 12
87.5K Views
Medium Frequency
~25 min Avg. Time
891 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