c - Binary tree mirror() how does this work? -


i have had real difficulty in understanding core of snippet though looks simple , straightforward. given simple binary tree, famous function produces mirrored result of same tree.

void mirror(struct node* node) {   if (node==null) {     return;   }   else {     struct node* temp;      // subtrees     mirror(node->left); //this part confuses me     mirror(node->right); //so       // swap pointers in node     temp = node->left;     node->left = node->right;     node->right = temp;   } } 

this code. have 2 questions on mind after reading code.

  1. mirror(node->left) , mirror(node->right) places 2 consecutive function calls on call stack. understanding is, first, function called on left node , right. process recurs long node empty. when not empty return? come call statement without returning anything?

  2. how these functions invoked call stack? helpful if runs through function calls , tells how , why need 2 consecutive function calls.

p.s: why aren't iterations used in scope?

edit: quoting useful comment eof, possible tail-recurse function moving swapping before 2 recursive calls?

  1. mirror(node->left) , mirror(node->right) places 2 consecutive function calls on call stack.

that's odd way put it, , may reflect misunderstanding. @ no 1 time call stack ever contains representation of both function calls.

my understanding is, first, function called on left node , right. process recurs long node empty. when not empty return?

the function has type void. never returns anything.

does come call statement without returning anything?

yes, when function finishes, control resumes next statement after function call.

  1. how these functions invoked call stack?

functions not invoked "from" call stack. stack frames created functions , pushed part of process of calling function. details unspecified; compilers responsible generating code right thing.

it helpful if runs through function calls , tells how , why need 2 consecutive function calls.

to mirror whole tree means reverse children of every node. when processing given node, function must therefore ensure that node's children both mirrored. accomplishes performing recursive call each one, , afterward swaps them.


Comments