I had an interview and I could not answer this question. You have an binary tree and you are putting all the nodes into an array using in_order and you return the value for the size of the array. I was told that I could not use a helper function and add int i=0 for an array counter.
The recursive function heading I had to use was.
In_order(Struct_Node * node, int *array){
}
Because it was In_order I wrote.
if(node){
In_order(node->left, array);
//this line is where I am supposed to add the elements and return the value,
but I do not understand how to do this. This is my week point and I need to understand
the reasoning of how this code works more than what is the code.
in_order(node->right,array);
}
I didn’t actually write what I wrote in between the two In_order statements but what I wrote was wrong.
Guessing all the missing details I think you would do something like:
The key point is you pass an updated pointer to the RHS recursive call and your return value is
1 + LHS return + RHS returnIf you can’t use an int as a counter (which is silly really because it’s by far the clearest way of expressing it) you can do:
If you wanted to go “a little” crazy and avoid any locals other than the function arguments you could change the return type to be a pointer to the current working end of the array (which is in effect the size of the array also) and do:
Although to be quite honest that’s terrible code (I’m not even 100% sure that it is well defined!) and I really hope they weren’t looking for a solution like that!