Can someone please explain how a locally initialized object in this case "root, is able to have Left and Right properties assigned with Node objects in previous recursion stages, without passing root as function argument.
I suspect this effect is due to return statement returning Node object reference in previous Recursion stages.
However, my understanding is that return statement is simply ending function call by removing function from Stack, only the "first original" function before any recursion started will return actual value.
Codes in C#
private Node<int> TestLocalVariableRecursion(int start)
{
Node<int> root = null;
if(start < 5)
{
root = new Node<int>(start);
root.Left = TestLocalVariableRecursion(start + 1);
root.Right = TestLocalVariableRecursion(start + 2);
}
return root;
}
public class Node<T>
{
public Node(T value)
{
Value = value;
}
public T Value { get; set; }
public Node<T> Left { get; set; }
public Node<T> Right { get; set; }
}
result of root: https://i.stack.imgur.com/qdJqQ.png