Skip to content
Advertisement

How does parameters of a method get stored in stack during a recursive call?

I was doing a leetcode question https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree-ii/ and I am confused on how parameters for a method get stored during a recursive call.

If a node gets visited, I wanted to save it’s state that it was visited. When I send two variables, when the stack is getting unwinded the updated variable values are being lost.

JavaScript

But if I send an array and update values inside the array and pass the array itself as a parameter during recursion then the updated variable values are getting persisted.

JavaScript

I feel like I am missing some basic knowledge here, can anyone please help me understand how the two code’s are different and any material I can read to improve my knowledge on stack and recursion?

Advertisement

Answer

The issue has less to do with “recursion” and more to do with the function call itself.

When you’re calling foo(var1, var2), the variables get passed by value. The changes you make inside the function block aren’t propagated outside the function.

When you pass the array, it gets passed by reference/pointer. Any modifications made to it are made to it’s actual memory, so the changes gets retained/reflected even outside the function block.

You can read more on the differences between passing by value and reference here.

Edit:
Java is “always” pass-by-value because objects have references which are getting passed by value. This confusing terminology is clarified here in detail.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement