JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

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.

Example 1:

img

Input: root = [5,10,10,null,null,2,3]
Output: true

Example 2:

i

Input: root = [1,2,10,null,null,2,20]
Output: false
Explanation: You cannot split the tree into two trees with equal sums after removing exactly one edge on the tree.

Constraints:

  • The number of nodes in the tree is in the range $[1, 10^4]$.
  • $-10^5 <= Node.val <= 10^5$

Code

    0
   / \
  -1  1
class Solution {
    public boolean checkEqualTree(TreeNode root) {
        HashSet<Integer> set = new HashSet<>();

        int left = helper(root.left, set);
        int right = helper(root.right, set);

        int sum = left + right + root.val;
        return sum % 2 == 0 && set.contains(sum / 2);
    }

    private int helper(TreeNode root, HashSet<Integer> set) {
        if(root == null) return 0;

        int left = helper(root.left, set);
        int right = helper(root.right, set);

        int curr = root.val + left + right;
        set.add(curr);

        return curr;
    }
}
class Solution {
    boolean find = false;
    public boolean checkEqualTree(TreeNode root) {
        int sum = getSum(root);
        if(sum % 2 != 0) return false;

        findSum(root.left, sum / 2);
        findSum(root.right, sum / 2);

        return find;
    }

    private int findSum(TreeNode root, int sum) {
        if(root == null) return 0;

        int left = findSum(root.left, sum);
        int right = findSum(root.right, sum);

        int curr = root.val + left + right;
        if(curr == sum) find = true;

        return curr;
    }

    private int getSum(TreeNode root) {
        if(root == null) return 0;

        int left = getSum(root.left);
        int right = getSum(root.right);

        return root.val + left + right;
    }
}