Why doesn't this work? Stuck on using global variable. (Javascript)


  • 0
    J

    Seems like this should be working, any idea why it's not? Interestingly enough, when I set tilt to an object it does work. My hunch is it has something to do with recursion and global variable value timings but unsure. Would appreciate any pointers or illumination.

    Fails:

    let tilt = 0;
    var findTilt = function(root) {
        dfs(root);
        return tilt;
    };
    
    var dfs = function(root) {
        if (!root) {
            return 0;
        }
        
        let left = dfs(root.left);
        let right = dfs(root.right);
        
        tilt += Math.abs(left - right);
        
        return root.val + left + right;
    }
    

    Works:

    var findTilt = function(root) {
        const tilt = { val: 0 }
        dfs(root);
        return tilt.val;
    };
    
    var dfs = function(root) {
        if (!root) {
            return 0;
        }
        
        let left = dfs(root.left);
        let right = dfs(root.right);
        
        tilt.val += Math.abs(left - right);
        
        return root.val + left + right;
    }

  • 1
    M

    @jordan34 it's because a node.js module is being used to execute the JavaScript on leetcode, and if you console.log(this) you get an empty object, because you're in an empty node module. So when you define let tilt = 0 or var tilt = 0 on that module, that scope is outside of the function calls.

    I think it's not set up that intuitively since the other languages on here let you scope variables globally.

    I think the easiest fix is to consider the solution function your global scope, like this:

    var findTilt = function(root) {
        let tilt = 0;
        var dfs = function(root) {
            if (!root) {
                return 0;
            }
            
            let left = dfs(root.left);
            let right = dfs(root.right);
            
            tilt += Math.abs(left - right);
            
            return root.val + left + right;
        }
        dfs(root);
        return tilt;
    };
    

    Also can use an IIFE, see my solution.


  • 0
    J

    @mhueter That's very interesting, thanks so much! I understood both methods, I was just super confused as to why it was happening. Thanks again.


Log in to reply
 

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