How to use return function in recursion - c++

I am having this below code for inorder traversal of tree:
void inOrder(struct node* r)
{
if (r==NULL)
return;
else
{
inOrder(r->left);
printf("%d ", r->value);
inOrder(r->right);
}
}
I am having this silly doubt:
When the bottom most left child is passed as root, it is not null.
In the next iteration root will be null (as left child of bottom most left child will be null) and it will encounter return.
Wont this return statement pass the control to main function (or wherever it is called) without printing anything?
Does return behave differently in recursion?

This return will pass the control back to the position where the current "layer" of function is called.
Function calls are organized in a structure called stack. Imagine that there is a box in your computer. The computer can put an element into the box(on top the other elements in the box), or it can remove the element at the top of the box. Consider the following code.
void f(int x)
{
if (x == 0)
return;
f(x - 1);
}
If you call f(2) in the main function, the computer puts f(2) into the box. When f(2) is executed, it calls f(1) inside the function, so the computer puts f(1) into the box(on top of f(2)). As f(1) also calls f(0), the computer puts f(0) into the box.
When f(0) is executed, nothing is called and it meets the return instruction. So the computer removes f(0) from the box, and f(1) is now on top of the box. So your computer knows that it is f(1) rather than main that calls f(0), so it will continue executing f(1). It is the same when f(1) is returned.

When the bottom most left child is passed as root, it is not null.
void inOrder(struct node* r)
{
if (r==NULL)
return;
else{
inOrder(r->left);
printf("%d ", r->value);
inOrder(r->right);
}
}
In your above code when you pass the bottom most left child as root.
It first executes this line
if (r==NULL) return;
as r is not null currently it will skip this return.
In the else part it would now execute
else{
inOrder(r->left);
Here, It is calling the same function again so, the current execution will pause for a moment and resume when this call returns.
Now, inOrder(r->left); call inOrder(struct node* r); again with null as parameter r to this call. since, you are passing r->left which is null.
so, this call to inorder will hit return
if (r==NULL) return;
As it returns it will resume last instance of inorder call which paused at
inOrder(r->left); call.
This is possible because whenever you call a function from inside a
function is maintains a call stack.
Now, after resuming it will execute the next line
printf("%d ", r->value);
Which will print the value in your bottom left most node.
finally, it will call the last line
inOrder(r->right); which will again pause the execution of current function and after saving the current state of function in call stack it will call the inorder with null again r->right which will return again from
if (r==NULL) return;
and finally it will come back to original execution of inorder and resume and as there are no instruction left it will return to the main method if you called from there and resume what left in main.
so, your answer is it will print only the value in the bottom most left node.

A classical example of recursion might better illustrate the problem
int factorial(int n)
{
if(n == 0)
return 1;
return n * factorial(n - 1);
}
If we were to call factorial(3), it will recursively call factorial till the base case n == 0, at which point, will return the control flow to the point where it was called, which is factorial(1) and not main.
So, no, your return statement goes back to the parent node where the function was called.

Related

How to transform a recursive function to an iterative one

I'm trying to convert this recursive function to an iterative one using a stack:
void GetToTownRecursive(int x, Country &country, AList *accessiblesGroup, vector<eTownColor> &cities_colors)
{
cities_colors[x - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(x);
List *connected_cities = country.GetConnectedCities(x);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == eTownColor::WHITE)
{
GetToTownRecursive(curr_city->GetTown(), country, accessiblesGroup, cities_colors);
}
curr_city = curr_city->GetNextNode();
}
}
}
The function takes a town number as an input and returns a list of towns that are connected to that town (directly as well as indirectly).
I'm having difficulty converting it because of the while loop within and because the only action taken after the recursive call is the promotion of the list iterator - curr_city. What should I push into the stack in this case?
Would be glad for your help!
The action taken after the recursive call is the whole remainder of the while loop (all the remaining iterations). On the stack, you have to save any variables that could change during the recursive call, but will be needed after. In this case, that's just the value of curr_city.
If goto was still a thing, you could then replace the recursive call with:
save curr_city
set x = curr_city->GetTown()
goto start
Then at the end, you have to
check stack
If there's a saved curr_city, restore it and goto just after (3)
Because it's not acceptable to use gotos for this sort of thing (they make your code hard to understand), you have to break up your function into 3 top-level parts:
part 1: all the stuff before the first recursive call, ending with 1-3
part 2: a loop that does all the stuff between recursive calls, ending with 1-3 if it gets to another recursive call, or 4-5 if it doesn't.
part 3: anything that happens after the last recursive call, which is nothing in this case.
Typically there is then a lot of cleanup and simplification you can do after this rearrangement.
The basic idea would be something like the following.
void GetToTown(int x, Country &country, AList *accessiblesGroup,
vector<eTownColor> &cities_colors)
{
Stack<int> pendingX = new ...
pendingX.push(x);
while (!pendingX.isEmpty()) {
int localX = pendingX.Pop();
cities_colors[localX - 1] = eTownColor::BLACK;
accessiblesGroup->Insert(localX);
List *connected_cities = country.GetConnectedCities(localX);
if (!connected_cities->IsEmpty())
{
ListNode *curr_city = connected_cities->First();
while (curr_city != nullptr)
{
if (cities_colors[curr_city->GetTown() - 1] == nColor::WHITE)
{
pendingX.Push(curr_city->GetTown());
}
curr_city = curr_city->GetNextNode();
}
}
}
}

recursive function calling in c++

Whats the difference between
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
and
return(checkBst(root->left, minvalue, root));
return(checkBst(root->right, root, maxvalue));
My whole programme looks like this
bool checkBst(node *root, node * minvalue, node * maxvalue){
if(root == NULL){
return true;
}
if((minvalue && root->data <= minvalue->data) || (maxvalue && root->data >= maxvalue->data)){
return false;
}
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
// return(checkBst(root->left, minvalue, root));
// return(checkBst(root->right, root, maxvalue));
}
To be frank, you cannot have a return for each of the function calls. This is because return is the last statement executed in a function before the control is given back to the calling function.
In your case, the second function is NEVER called. So, if your first function returns true, it never calls the 2nd function. Had the 2nd function result been false, the answer you get will be erroneous.
You still need to have a return statement at the end of both statements and capture the value returned by the functions.
I mean this statement:
return(checkBst(root->left, minvalue, root) && checkBst(root->right, root, maxvalue));
is equal to:
ret1 = checkBst(root->left, minvalue, root);
if(ret1)
return checkBst(root->right, root, maxvalue);
else
return false;
Recursion is not about putting everything in one line. That is just a coding style. The Comment by Pepijn Kramer and Some programmer dude talk about the optimization that you can get with writing in the same line. If the 1st half is false, you don't need to evaluate the 2nd half and that saves computation time and energy.
Recursion is about doing repetitive tasks by calling the same function within itself and using the result of it to give the final result.
In your case, Initially you send the whole tree. Then you divide the problem into 2 halves by calling the function for each of the sub-trees.
In each function call you take care of the terminal conditions. That is the first and second lines that you have. Those are the only cases where you don't call more functions. You are getting a return value.
Now, this return value should be propagated back to the calling function

Recursive function to return last node of a heap

I am trying to return the last node of a binary heap (implemented with pointers, not an array). Here, 'last' means the bottom-most node starting from the left in this case without two children, actually the node where I am supposed to append the new node to. The insert function will bind data to a new node for insertion, then call this function to return the last node, so I can add the new node either left of right depending on the child nodes present, or not.
The problem is that the right side of the tree is always empty, and never gets past the height after root's. Seems to stick on the leftmost side, because it reaches first the exit condition from every recursion call starting from left.
The recursive function checks first the node, returns 0 if no child, returns 1 if only left child and returns 2 in case of a node having two children. Here is the function :
template<typename T>
node<T> * heap<T>::find_insert_pos (node<T> *x, int &res) {
if(find_insert_poshelper(x, res) == 0) return x;
else if(find_insert_poshelper(x, res) == 1) return x;
else {
node<T> *a = find_insert_pos(x->left, res);
if(find_insert_poshelper(a, res) != 2) return a;
else return find_insert_pos(a, res);
node<T> *b = find_insert_pos(x->right, res);
if(find_insert_poshelper(b, res) != 2) return b;
else return find_insert_pos(b, res);
}
}
I've tried to figure it out, but insertion still goes wrong. The other functions used into insertion are more than triple checked.
(By the way, 'res' is passed by reference always in the chunk of code)
I have changed the logic behind the function. Instead of only validating for children per node, I validate now if the node evaluated had children, if it does then I validate one step further each of those children, left and right, to see if any of those grand-children have children themselves.
If they don't, I will loop this for the next level following the root level 0, jumping to level 1 and so on, until one of the children nodes does not contain two children, and returning x.left or x.right, depending the case.
-- Final edit --
Hard to think about a MRE since it was more about logic. The question was posted by someone in need of practice with recursion, and it happened. All the logic changed, even for sub-functions.
But it will be required to manually assign and narrow down until three levels are full (full meaning having two children) before calling this operation, which is checking three levels down. Having this done nicely I get a beautiful heap.
I can show an attempt to a MRE of how I implemented it to be able to find the bottom node to append a new node to, but not pure since I don't put the code from the 'insert' function, which is part iterative (first three levels) and part recursive (that was the original question, to find the parent node for the new node to insert). How the insert operation goes, I create a new node dynamically and then I search for the parent node where I need to append new data to (the iterative part starts here until the 8th node of the tree is reached, path similar to BFS), then when the position is retrieved (that is, the pointer itself), I test whether for left or right insertion, as by the rules of the heap. Starting at the 8th node, the value of the parent node is set recursively as follows :
First the recursive function itself :
node * function_a (node *x, int &res) {
node *temp = function_b (x, res);
if(temp != ptr_null) return temp;
else {
if(x->L != ptr_null) function_a (x->L, res);
if(x->R != ptr_null) function_a (x->R, res);
return temp;
}
}
A sub-function :
node * function_b (node *x, int &res) {
node *a = x->L;
node *b = x->R;
int aL = function_c (a->L, res);
int aR = function_c (a->R, res);
int bL = function_c (b->L, res);
int bL = function_c (b->R, res);
if(aL != 2) return a->L;
else if(aR != 2) return a->R;
else if(bL != 2) return b->L;
else if(bR != 2) return b->R;
else return ptr_null;
}
And another :
int & function_c (node *x, int &res) {
if(x->L == ptr_null && x.R == ptr_null) return res = 0;
else if(x->L != ptr_null && x->R == ptr_null) return res = 1;
else return res = 2;
}
Since this is checking 3 levels down from x defined (in this case from the root) in function_a, I can't make it 100% recursive that way or I will get a segmentation fault. How can I improve my algorithm ?

What is happening in this function?

I was looking for a method to display the contents of Binary search tree in inorder method. I found this method which seems quite popular but I cannot understand how is this recursion working. How will the code ever reach cout? Also root node is being passed into the function when called by the main function. EDIT: This is considering that "root!=NULL".
void display(struct tree *p)
{
while(p!=NULL)
{
display(p->left);
cout<<p->data;
display(p->right);
}
}
First of all, instead of while(p!=NULL) you should use if (p != null). Otherwise, you get an infinite loop in case the root node is not null.
It first displays the left subtree calling recursively display(p->left). After that it displays the node itself (cout<data) and finally the right subtree calling recursively display(p->right).
Suppose you have the following tree:
4
2 6
1 3 5
A call to display(root), results in the following function calls:
display(4)
display(2)
display(1)
display(null)
cout 1
display(null)
cout 2
display(3)
display(null)
cout 3
display(null)
cout 4
display(6)
display(5)
display(null)
cout 5
display(null)
cout 6
display(null)
When the function is called for node "1", it first displays the left subtree by calling display(p->left).
That function notices p==null returning therefore directly.
So control returns to display(1).
The next statement is cout << 1.
After that, it displays the right subtree by calling display(p->right).
That function notices p==null returning therefore directly.
So again, control returns to display(1).
At this point, display(1) has terminated and control returns to the function that called display(1), being display(2).
It finished its call to display(p->left) (being "1") and therefore executes it next statement, which is cout << 2.
The reason that the code will reach cout is that function display will not recurse all the time.
Once the parameter passed to display become NULL,that is,you have reached the leaf node of that tree, the recursion will start to trace back,the stack will start unwinding.Finally the control will return to the origin call of display.And it begins to execute the cout.
And that's why the judgement while(p!=NULL) is indispensable.

printing the contents of a Binary Search Tree recursively?

void MovieTree::printMovieInventory(MovieNode* node)
{
if(node)
{
while(node->rightChild!=NULL or node->leftChild!=NULL)
{
std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
if(node->rightChild)
{
printMovieInventory(node->rightChild);
}
if(node->leftChild)
{
printMovieInventory(node->leftChild);
}
}
}
else
{
std::cout<<"No movies in list!"<<std::endl;
}
}
I'm not sure if this function is causing my issue or if it's my adding function but I feel as though the logic to this is correct. Am I missing something?
Edit::
My issue is that it's resulting in an infinite loop and it's not properly printing all associated children of the tree
Use of while in the function is wrong. It needs to be if. Otherwise, the function never breaks out of the while loop.
FWIW, that function can be simplified to:
void MovieTree::printMovieInventory(MovieNode* node)
{
if(node)
{
std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
printMovieInventory(node->rightChild);
printMovieInventory(node->leftChild);
}
}
In addition to the problem with the while loop, this can also never print leaf nodes, as you don't print the node itself if it doesn't have either a left or a right child.
while(node->rightChild!=NULL or node->leftChild!=NULL)
{
std::cout<<"Movie:"<<node->title<<" "<<node->quantity<<std::endl;
it should be
if(node)
print node
if left
recurse left
if right
recurse right
Couple of Things here.
From the code as i understand, you are trying to print in a pre-order fashion.
the While Loop is unnecessary and that is what is causing the infinite loop
Lets say you have two nodes root and root->left
your function will print root, call the function recursively on root' = root->right (will not print anything this time because root'->left is NULL and root'->right is NULL). Then the function print(root') returns to its caller which is print(root). This time it will not exit out of the while Loop because the while condition is always true, ergo the infinite Loop.
you can simply do this
Print(root)
cout << root;
if(root->right != NULL)
Print(root->right);
if(root->left != NULL)
Print(root->left);
TO display "No Movies" just check if root == NULL before calling this recursive function Print(root);