663. Equal Tree Partition
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks if we can partition a binary tree into two smaller trees of equal value-sum by removing exactly one edge.
Solution
Equal Tree Partition in Python
# 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: Optional[TreeNode]) -> bool:
# A list to store the sum of each subtree encountered during traversal.
sums = []
# Helper function to perform post-order traversal.
# It calculates the sum of the subtree rooted at `node`,
# appends it to the `sums` list, and returns the sum.
def get_subtree_sum(node):
# Base case: if the node is null, its subtree sum is 0.
if not node:
return 0
# Recursively calculate sums of left and right subtrees.
left_sum = get_subtree_sum(node.left)
right_sum = get_subtree_sum(node.right)
# The sum of the current subtree is the node's value plus sums of its children's subtrees.
current_sum = node.val + left_sum + right_sum
# Store the sum of this subtree.
sums.append(current_sum)
return current_sum
# First pass: Calculate the total sum of the tree and populate the `sums` list.
# Python's integers handle arbitrary size, so no overflow worries.
total_sum = get_subtree_sum(root)
# The last sum added is the sum of the entire tree. We remove it because
# a partition requires removing an edge, so we can't select the whole tree.
sums.pop()
# If the total sum is odd, it's impossible to partition it into two equal integer sums.
if total_sum % 2 != 0:
return False
# The target sum for a valid partition is half of the total sum.
target = total_sum / 2
# Second pass: Check if any of the proper subtrees (all subtrees except the whole tree)
# has a sum equal to the target.
return target in sums
Equal Tree Partition in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// A list to store the sum of each subtree encountered during traversal.
private List<Long> sums;
public boolean checkEqualTree(TreeNode root) {
sums = new ArrayList<>();
// First pass: Calculate the total sum of the tree and populate the `sums` list
// with all subtree sums. Using long to prevent potential integer overflow.
long totalSum = getSubtreeSum(root);
// If the tree has only one node, it's impossible to partition.
// In our logic, `sums` will have one element (totalSum), which we pop.
// The list becomes empty, so the check for target will fail, which is correct.
// The last sum added is the sum of the entire tree. We remove it because
// a partition requires removing an edge, which means we can't select the whole tree.
sums.remove(sums.size() - 1);
// If the total sum is odd, it's impossible to partition it into two equal integer sums.
if (totalSum % 2 != 0) {
return false;
}
// The target sum for a valid partition is half of the total sum.
long target = totalSum / 2;
// Second pass: Check if any of the proper subtrees (all subtrees except the whole tree)
// has a sum equal to the target.
return sums.contains(target);
}
// Helper function to perform post-order traversal.
// It calculates the sum of the subtree rooted at `node`,
// adds it to the `sums` list, and returns the sum.
private long getSubtreeSum(TreeNode node) {
// Base case: if the node is null, its subtree sum is 0.
if (node == null) {
return 0;
}
// Recursively calculate sums of left and right subtrees.
long leftSum = getSubtreeSum(node.left);
long rightSum = getSubtreeSum(node.right);
// The sum of the current subtree is the node's value plus sums of its children's subtrees.
long currentSum = node.val + leftSum + rightSum;
// Store the sum of this subtree.
sums.add(currentSum);
return currentSum;
}
}
Equal Tree Partition in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
// A vector to store the sum of each subtree encountered during traversal.
std::vector<long long> sums;
// Helper function to perform post-order traversal.
// It calculates the sum of the subtree rooted at `node`,
// adds it to the `sums` vector, and returns the sum.
long long getSubtreeSum(TreeNode* node) {
// Base case: if the node is null, its subtree sum is 0.
if (!node) {
return 0;
}
// Recursively calculate sums of left and right subtrees.
long long leftSum = getSubtreeSum(node->left);
long long rightSum = getSubtreeSum(node->right);
// The sum of the current subtree is the node's value plus sums of its children's subtrees.
long long currentSum = node->val + leftSum + rightSum;
// Store the sum of this subtree.
sums.push_back(currentSum);
return currentSum;
}
public:
bool checkEqualTree(TreeNode* root) {
// Clear the sums vector for multiple test cases.
sums.clear();
// First pass: Calculate the total sum of the tree and populate the `sums` vector
// with all subtree sums.
long long totalSum = getSubtreeSum(root);
// After the traversal, the last element in `sums` is the sum of the entire tree.
// We remove it because we cannot cut the edge "above" the root.
sums.pop_back();
// If the total sum is odd, it's impossible to partition it into two equal halves.
if (totalSum % 2 != 0) {
return false;
}
// The target sum for a valid partition is half of the total sum.
long long target = totalSum / 2;
// Second pass: Check if any of the proper subtrees has a sum equal to the target.
for (long long s : sums) {
if (s == target) {
return true;
}
}
return false;
}
};
Equal Tree Partition in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function checkEqualTree(root: TreeNode | null): boolean {
// A list to store the sum of each subtree encountered during traversal.
const sums: number[] = [];
// Helper function to perform post-order traversal.
// It calculates the sum of the subtree rooted at `node`,
// adds it to the `sums` array, and returns the sum.
const getSubtreeSum = (node: TreeNode | null): number => {
// Base case: if the node is null, its subtree sum is 0.
if (node === null) {
return 0;
}
// Recursively calculate sums of left and right subtrees.
const leftSum = getSubtreeSum(node.left);
const rightSum = getSubtreeSum(node.right);
// The sum of the current subtree is the node's value plus sums of its children's subtrees.
const currentSum = node.val + leftSum + rightSum;
// Store the sum of this subtree.
sums.push(currentSum);
return currentSum;
};
// If the root is null, no partition is possible.
if (root === null) {
return false;
}
// First pass: Calculate the total sum of the tree and populate the `sums` array.
const totalSum = getSubtreeSum(root);
// The last sum added is the sum of the entire tree. We remove it because
// a partition requires removing an edge, so we can't select the whole tree.
sums.pop();
// If the total sum is odd, it's impossible to partition it into two equal integer sums.
if (totalSum % 2 !== 0) {
return false;
}
// The target sum for a valid partition is half of the total sum.
const target = totalSum / 2;
// Second pass: Check if any of the proper subtrees (all subtrees except the whole tree)
// has a sum equal to the target.
return sums.includes(target);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.