LeetCode 663: Equal Tree Partition Solution

Master LeetCode problem 663 (Equal Tree Partition), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

663. Equal Tree Partition

Problem Explanation

Explanation

To solve this problem, we need to determine if a binary tree can be split into two trees of equal sum by removing one edge. We can achieve this by performing a depth-first search to calculate the sum of the entire tree. Then, we can check if there exists a subtree with half the total sum. If such a subtree exists, we can remove the edge leading to that subtree to achieve equal partition.

  1. Perform a DFS traversal to calculate the total sum of the binary tree.
  2. Perform another DFS traversal to find a subtree with sum equal to half the total sum.
  3. If such a subtree is found, return true; otherwise, return false.

Time Complexity: O(n) where n is the number of nodes in the binary tree. Space Complexity: O(n) for the recursion stack.

Solution Code

class Solution {
    public boolean checkEqualTree(TreeNode root) {
        int totalSum = getTreeSum(root);
        if (totalSum % 2 != 0) return false;
        return checkSubtreeSum(root, totalSum / 2).contains(totalSum / 2);
    }
    
    private Set<Integer> checkSubtreeSum(TreeNode node, int target) {
        Set<Integer> subtreeSums = new HashSet<>();
        if (node == null) return subtreeSums;
        subtreeSums.add(node.val + checkSubtreeSum(node.left, target).stream().mapToInt(Integer::intValue).sum());
        subtreeSums.add(node.val + checkSubtreeSum(node.right, target).stream().mapToInt(Integer::intValue).sum());
        return subtreeSums;
    }
    
    private int getTreeSum(TreeNode node) {
        if (node == null) return 0;
        return node.val + getTreeSum(node.left) + getTreeSum(node.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 663 (Equal Tree Partition)?

This page provides optimized solutions for LeetCode problem 663 (Equal Tree Partition) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 663 (Equal Tree Partition)?

The time complexity for LeetCode 663 (Equal Tree Partition) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 663 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 663 in Java, C++, or Python.

Back to LeetCode Solutions