Simple solution with only HashSet


  • 0
    R
    class Solution {
        public boolean checkEqualTree(TreeNode root) {
            HashSet<Integer> sums = new HashSet<>();
            int total = findSums(root, sums);
            if (total % 2 == 0) return sums.contains(total / 2);
            else return false;
        }
        int findSums(TreeNode node, HashSet<Integer> sums) {
            if (node == null) return 0;
            int left = findSums(node.left, sums);
            int right = findSums(node.right, sums);
            if (node.left != null) sums.add(left);
            if (node.right != null) sums.add(right);
            return left + right + node.val;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.