Java (sum - bottom to top subtree's sum = subtree's sum)


  • 0
    H
        int sum = 0;
    
        public class Result{
            boolean equalTree;
            int sumCurrent;
        }
    
        public boolean checkEqualTree(TreeNode root) {
            if(root==null || (root.left==null && root.right==null)) return false;
            sumTree(root);
            Result result = helper(root);
            return result.equalTree==true;
        }
    
        private Result helper(TreeNode root){
            if(root==null){
                return new Result();
            }
            
            Result resultLeft = helper(root.left);
            Result resultRight = helper(root.right);
    
            Result result = new Result();
            if(resultLeft.equalTree || resultRight.equalTree) {
                result.equalTree=true;
                return result;
            }
            result.sumCurrent = resultLeft.sumCurrent + resultRight.sumCurrent + root.val;
    
            if(sum-resultRight.sumCurrent == resultRight.sumCurrent || sum-resultLeft.sumCurrent == resultLeft.sumCurrent) {
                result.equalTree = true;
            }
            return result;
        }
    
    
        public void sumTree(TreeNode root) {
            if(root==null) return;
            sum+=root.val;
            sumTree(root.left);
            sumTree(root.right);
        }
    

Log in to reply
 

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