Reputation: 161
How is value 1 passed to the if statement in main function and how does the return function work with a recursive call in it?
#include <stdio.h>
#include <stdlib.h>
int identicalTrees(struct node* a, struct node* b)
{
if (a==NULL && b==NULL)
return 1;
if (a!=NULL && b!=NULL)
{
return
(
a->data == b->data &&
identicalTrees(a->left, b->left) &&
identicalTrees(a->right, b->right)
);
}
return 0;
}
int main()
{
if(identicalTrees(root1, root2))
printf("Both tree are identical.");
else
printf("Trees are not identical.");
getchar();
return 0;
}
Upvotes: 0
Views: 279
Reputation: 506
When a method that has been declared to return a value is called, space is reserved on the stack for the return value each time that method is called. The Return statement places the value in that position on the stack and exits the method returning back to the code that called the method. The code that called the method retrieves the value put on the stack by the Return statement and uses it in the If statement.
In recursion, each successive call to a method has its own local stack variable space added to the top of the stack. When a method executes, the current top of stack pointer is decremented to "free" that method's stack space.
See http://en.wikipedia.org/wiki/Stack-oriented_programming_language and http://en.wikipedia.org/wiki/Recursion_(computer_science) and https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/recursion2.html for more detailed explanations.
Upvotes: 4