I am not able to understand the recursion of functions. How it works? how the values are stored and all?
int tree_size(struct node* node) {
if (node==NULL) {
The analogy with using pieces of paper (by @nhahtdh in the comments to Q) is very good. Let me elaborate on it.
First, re-write your code in more linear manner:
int tree_size(struct node* node) {
if (node==NULL) {
return(0);
} else {
x = tree_size(node->left);
y = tree_size(node->right);
z = x + y;
r = z + 1;
return( r );
}
}
Imagine you have a thick (practically inexhaustible) stack of empty sheets of paper in front of you. You also have various recipes (function definitions) to the left of you on your desk, and an empty space to the right of you.
Now, to call a function means to copy its definition from its recipe onto the sheet of paper on top of the stack of papers in front of you, then substitute the argument values of the call for the function parameters, and go on from there.
When you hit a line with a function call on it (any function call), mark that line on the sheet of paper in front of you, move that paper to your right (faced up), and start working on the new empty sheet of paper in front of you. Copy onto it the recipe for the function that you need to call, write down the argument values, and continue working on it according to the recipe now in front of you.
If you encounter another function call, repeat this sequence of actions: mark the line that needs to receive the result of the function call, put your current sheet of paper on top the pile to your right (facing up), copy the new recipe on the top sheet of paper in front of you, and go on from there as before.
Now when you hit a line in the current recipe that says return
, write down the returned value onto the top sheet of paper in the pile to your right on the marked line there, then discard the current piece of paper in front of you and move back the top piece of paper from the stack of papers to you right onto the stack of papers in front of you.
That's it. All you needed were the two stacks of sheets of paper, one in front of you, and another one to your right, and the pile of papers with functions' definitions written on them, to your left.
Notice, we don't care if the function that we call is the same as one of the previous function calls that we performed, or not. It works just the same.