This problem asks whether a binary tree can be partitioned into two subtrees with equal sums by removing exactly one edge. The solution uses a depth-first search (DFS) approach to efficiently calculate the sum of each subtree and check for a partition.
Algorithm:
Sum Calculation: A recursive helper function sum
calculates the sum of each subtree rooted at a given node. It traverses the tree recursively, adding the node's value to the sum of its left and right subtrees. The sum of each subtree encountered during traversal is stored in a list seen
.
Total Sum and Check for Odd Sum: The checkEqualTree
function first calls sum
to compute the total sum (s
) of the entire tree. If the total sum is odd, it's impossible to partition the tree into two equal sums, so the function returns false
.
Removing the Root's Sum: The last element added to seen
corresponds to the sum of the entire tree (including the root). This is removed because we need to consider partitions created by removing an edge, which would exclude the root itself from one of the resulting subtrees.
Checking for Equal Partition: The function then checks if half of the total sum (s//2
or s/2
) exists in the seen
list. If it does, it means there's a subtree with a sum equal to half the total tree sum, implying a valid partition is possible. The function returns true
in this case; otherwise, it returns false
.
Time Complexity Analysis:
The time complexity is dominated by the DFS traversal of the tree. In the worst-case scenario (a skewed tree), the function visits each node once, resulting in O(N) time complexity, where N is the number of nodes in the tree.
Space Complexity Analysis:
The space complexity is determined by the recursive call stack during DFS and the seen
list. In the worst case (skewed tree), the recursive stack can grow up to O(N) deep. The seen
list also stores at most N subtree sums, so its space complexity is O(N). Therefore, the overall space complexity is O(N).
Code Explanation (Python):
The Python code implements this algorithm concisely. The sum
function recursively computes subtree sums, storing them in seen
. The checkEqualTree
function handles the initial sum calculation, the odd-sum check, and the final partition check. Note the use of seen.pop()
to remove the root's sum from consideration.
Code Explanation (Other Languages):
The Java, C++, and Go implementations follow the same logic as the Python code, adapting the syntax and data structures to each language's specifics. They utilize lists/vectors/slices to store the subtree sums and perform similar checks for odd sums and equal partitions. The core recursive strategy for sum computation and the overall approach remains consistent across all languages.