Are global variables bad in an interview setting?

Lets say I wanted to sum all nodes of a binary tree:

I can write the code like this:

private int sum = 0; 

public void sumNodes(Node root) {   
    if (root == null) {  
        return;  
    }  

    sum += root.data;  
    sumNodes(root.left);  
    sumNodes(root.right);   
} 

Or I can write it like this:

public int sumNodes(Node root) {   
    if (root == null) {  
        return 0;  
    }  
    return root.data + sumNodes(root.left) + sumNodes(root.right);
}

The first version is more intuitive IMO but the second version is preferred.

This particular problem is easy enough where I'd imagine that candidates should be able to solve the problem both ways, but I vastly prefer the former approach for more difficult problems.

I'm just wondering if mutating a global variable is discouraged in interview settings.

Comments (1)