I have had some real difficulty in understanding the core of this snippet though it looks very simple and straightforward. Given a simple Binary tree, this famous function produces a mirrored result of the same tree.
void mirror(struct node* node) {
if (node==NULL) {
return;
}
else {
struct node* temp;
// do the subtrees
mirror(node->left); //this part confuses me
mirror(node->right); //so does this
// swap the pointers in this node
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
This will be the code. I have two questions on my mind after reading this code.
mirror(node->left) and mirror(node->right) places two consecutive function calls on the call stack. My understanding is, first, the function is called on the left node and then right. This process recurs as long as node is empty. But when it is not empty what does it return? Does it just come back to the call statement without returning anything?
How are these functions invoked from the call stack? It would be really helpful if someone runs through the function calls and tells how and why do we need two consecutive function calls.
P.S: Why aren't iterations used in this scope?
EDIT: quoting a useful comment by EOF, is it possible to tail-recurse this function by moving the swapping before the two recursive calls?