Java solution, iterate twice


  • 0
    X

    First use sum() function to get the total sum of the treeNodes. And in the second iteration, use sum to check whether there is one subtree whose sum if total/2. If so, the flag will be set true.

    class Solution {
        boolean flag = false;
        int total = 0;
    
        public boolean checkEqualTree(TreeNode root) {
            if (root == null) return true;
            if (root.left == null && root.right == null) return false;
            total = sum(root, 0);
            flag = false;
            if (Math.abs(total) % 2 == 1) return false;
            sum(root, total / 2);
            return flag;
        }
    
        private int sum(TreeNode root, int total) {
            if (root == null) return 0;
            int sum = 0;
            sum = root.val + sum(root.left, total) + sum(root.right, total);
            if (sum == total) {
                flag = true;
            }
            return sum;
        }
    }
    

Log in to reply
 

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