0

In the code snippet below I am calling nodeDepths(root, depth, depthSum) and expecting updated value in depthSum but every time it's returning 0 to me

public static int nodeDepths(BinaryTree root) {
            Integer depthSum = 0;
            Integer depth = 0;
            nodeDepths(root, depth, depthSum);
            return depthSum;
    
        }
    
        public static void nodeDepths(BinaryTree root, int depth, Integer depthSum) {
            depth = depth + 1;
            depthSum = depthSum + depth;
    
            if (root.left == null && root.right == null) {
                return;
            }
    
            nodeDepths(root.left, depth, depthSum);
    
            nodeDepths(root.right, depth, depthSum);
    
        }

Note: I have not mentioned the problem scenario and logical part as that is not an issue. The issue I am facing is the "depthSum reference variable not getting updated in caller method"

Nishant Bhardwaz
  • 924
  • 8
  • 21

1 Answers1

0

Your line

depthSum = depthSum + 1

does not change depthSum object, but the binding of the local depthSum variable. Like any local variable updates, it will not propagate to the caller, because the caller only knows the original binding — that is why this call strategy is a subtype of call by value (where the value is the reference to an object).

In order to do what you want, you would need to do something like

depthSum.increment()
depthSum.add(1)
depthSum.setValue(depthSum.valueOf() + 1)

But unfortunately Integer is immutable, and no such methods exist. It is not possible to use call by object sharing strategy to update an Integer.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Thanks for the conceptual correction which I am doing. Can you suggest the alternative way to handle this? – Nishant Bhardwaz May 27 '21 at 02:29
  • Relying on mutables is frowned upon, particularly for such almost-primitive types, but you _could_ make your own `MutableInteger` that would contain an `int` that you could modify. A sounder approach is to explicitly return the return values from the function. – Amadan May 27 '21 at 02:33