Clean and passed code for all testcase


  • 2
    G
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private int sumTree = 0;
        private boolean res = false;
        public boolean checkEqualTree(TreeNode root) {
            if(root == null) return true;
            totalSum(root);
            dfs(root);
            return res;
        }
        private void totalSum(TreeNode root){
            if(root == null) return ;
            sumTree += root.val;
            totalSum(root.left);
            totalSum(root.right);
        }
        private int dfs(TreeNode root) {
            if(root.left == null && root.right == null) return root.val;
            int left = root.left != null ? dfs(root.left) : 0;
            int right = root.right != null ? dfs(root.right) : 0;
            int cur = root.val + left + right;
            if(!res && root.left != null && sumTree - left == left) res = true;
            if(!res && root.right != null && sumTree - right == right) res = true;
            return cur;
        }
    }

Log in to reply
 

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