[Java] Use ResultType to store the information that need to be passed


  • 1
    M

    Many posts use int array to store different max value of robbing root or not, I use a private class to store that, I think ResultType is very useful in many cases especially when you want to pass different kinds of values to hight level. Here is may code:

    public class Solution {
        private class ResultType {
            int includeRoot;
            int excludeRoot;
            public ResultType(int includeRoot, int excludeRoot) {
                this.includeRoot = includeRoot;
                this.excludeRoot = excludeRoot;
            }
        }
        public int rob(TreeNode root) {
            return Math.max(divideConquer(root).includeRoot, divideConquer(root).excludeRoot);
        }
        
        private ResultType divideConquer(TreeNode root) {
            if (root == null) {
                return new ResultType(0, 0);
            }
            ResultType left = divideConquer(root.left);
            ResultType right = divideConquer(root.right);
            int includeRoot = root.val + left.excludeRoot + right.excludeRoot;
            int excludeRoot = Math.max(left.includeRoot, left.excludeRoot)
                            + Math.max(right.includeRoot, right.excludeRoot);
            return new ResultType(includeRoot, excludeRoot);
        }
    }
    

Log in to reply
 

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