Simple Java Solution -- without Global Variable


  • 11
    L

    To avoid using global variable, you can take use of size-1 array or any other objects.

    public int findTilt(TreeNode root) {
        int[] ret = new int[1];
        helper(root, ret);
        return ret[0];
    }
        
    private int helper(TreeNode node, int[] ret){
        if(node == null){
            return 0;
        }
        int l_sum = helper(node.left, ret);
        int r_sum = helper(node.right, ret);
        ret[0] += Math.abs(l_sum - r_sum);
        return l_sum + r_sum + node.val
    }
    

  • 0

    Why not normal variable ?
    Normal variable will be stored into stack, and array (using new operator) in Heap memory,?


  • 3
    L

    @ruchit_tushar
    If using normal variable, you need to figure out how to update that variable globally among all recursive functions because of the property of call by value.


  • 0
    T

    @luckman
    I was using a normal variable, and the results is wrong. Thanks for your explanation.


Log in to reply
 

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