Divide Conquer insight


  • 0
    F
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     class ResultType{
            public int sum;
            public int tiltSum;
            public ResultType(int sum, int tiltSum){
                this.sum = sum;
                this.tiltSum = tiltSum;
            }
    } 
    public class Solution {
    
        public int findTilt(TreeNode root) {
            int tiltsum = 0;
            if (root == null){
                return 0;
            }
            return helper(root).tiltSum;
        }
        private ResultType helper(TreeNode root){
            if (root == null){
                return new ResultType(0, 0);
            }
            
            ResultType left = helper(root.left);
            ResultType right = helper(root.right);
            ResultType result = new ResultType(left.sum + right.sum + root.val, 
                                    left.tiltSum + right.tiltSum + Math.abs(left.sum - right.sum));
            return result;
        }
    }
    

Log in to reply
 

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