What is happening in this function? - c++

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.

Related

How to use return function in recursion

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.

Behavior of if versus while in a recursive C++ function

I'm new to C++, but I bumped into this problem on HackerRank and ran into a situation that seemed strange to me (coming from R/Python/Java):
https://www.hackerrank.com/challenges/tree-preorder-traversal
To give some background, the HackerRank problem was:
Complete the preOrder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values.
Input Format:
Our hidden tester code passes the root node of a binary tree to your preOrder function.
Input:
6
3 5 2 1 4 6
Expected Output:
3 5 1 4 2 6
I wrote this solution, which I thought would work:
//node is defined as:
/*
struct node
{
int data;
node* left;
node* right;
};
*/
void preOrder(node *root){
while (root != NULL){
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
return;
}
This code, though, never terminates and instead outputs:
3 5 1 1 1 1 1 1 1 1 1... (etc.)
What is strange and I am curious about is that if I change the while loop to the if conditional (as below) the program executes perfectly:
void preOrder(node *root){
if (root == NULL){
return;
}
cout << root->data << " ";
preOrder(root->left);
preOrder(root->right);
}
It is my understanding that both if and while ought to assess the condition each time preOrder() is called, but at some point, particularly after the 3rd iteration, the preOrder() function begins to continuously print 1 without terminating.
Any ideas, or could it be related to the main() code which I cannot see?
root can never become null within the context of the final call to preOrder.
A common mistake with recursion is to confuse variables with the same name at different levels of the stack. root from the first call to preOrder is not the same as root from the second call; rather, root from the second call is actually root->left or root->right from the first call. But as the recursion is unwinding, if you ever make it back out to the original call to preOrder, then you will once again be dealing with the original root.
When you hit a leaf node, you call preOrder with left and right which will both immediately return because the while loop will fail. Now you are back in the previous call to preorder, and root still points to the leaf node, not null. Within this context, root never changes, therefore how could it ever make it out of the while loop?
First of all,you have to see how preorder works you are using
while
than calling
preOrder(root->left);
preOrder(root->right);
but you have to store node's child in stack before calling next nodes otherwise all nodes are not not reached
// An iterative process to print preorder traversal of Binary tree
void iterativePreorder(node *root)
{
`// Base Case`
`if (root == NULL)`
`return;`
`// Create an empty stack and push root to it`
`stack<node *> nodeStack;`
`nodeStack.push(root);`
/* Pop all items one by one. Do following for every popped item
`a) print it`
`b) push its right child`
`c) push its left child`
Note that right child is pushed first so that left is processed first */
while (nodeStack.empty() == false)
{
`// Pop the top item from stack and print it`
` struct node *node = nodeStack.top();`
` printf ("%d ", node->data);`
` nodeStack.pop();`
`// Push right and left children of the popped node to stack`
` if (node->right)`
` nodeStack.push(node->right);`
`if (node->left)`
` nodeStack.push(node->left);`
}
}
here stack is used to store nodes

How does basecase influence which lines of recursive functions are used?

I have the following code in C++ for a recursive function. I don't understand why everything above the basecase is used before basecase is met (stacking?), and then only the lines below the basecase are used as its unstacking.
#include <iostream>
using namespace std;
void printnum(int begin)
{
cout << "upanddown";
cout << begin << endl; //Why is everything this line and above cout'd as it builds the stack and ignored on the unstacking.
if (begin <= 9) { printnum(begin + 1); } // Once the program starts unstacking the functions, why doesn't it console out "upanddown"?
e
cout << begin << endl; //Why is everything below the base case only shown as it unstacks?
}
int main()
{
printnum(1); //First function call, so it starts at one
system("PAUSE");
}
Which results in:
upanddown1
upanddown2
upanddown3
upanddown4
upanddown5
upanddown6
upanddown7
upanddown8
upanddown9
upanddown10
10
9
8
7
6
5
4
3
2
1
Press any key to continue . . .
Why doesn't upanddown execute below the base case ase well?
int main()
{
printnum(1); //First function call, so it starts at one
system("PAUSE");
}
Here is your main function. It has two statements. system("PAUSE"), which is the tail call¸ executed after printnum(1) has returned. To know where to continue it uses the stack for both indicating where to execute next and it's used to give functions arguments. Every call uses the stack so a recursive function is nothing special. The only special thing about it is that it happens to call itself, but the call to itself is independent and the current function is suspended until it has ended just like main. Consider your recursive function:
void printnum(int begin)
{
cout << "upanddown"; // 1
cout << begin << endl; // 2
if (begin <= 9) // 3
{
printnum(begin + 1); // 4
}
cout << begin << endl; // 5
}
So what happens if begin is 10? It will do 1, 2, 3, not 4, then 5.
Output is "upanddowdn10\n10\n".
For begin = 9 it will do 1, 2 which is "upanddown9\n", then the result of printnum(10) is printed since it hits your default case, then "9\n" is printed last. Thus the printed result is "upanddown9\nupanddowdn10\n10\n9\n"
For begin = 8 it will do 1, 2 which is "upanddown8\n", then the result of printnum(9) is printed since it hits your default case, then "8\n" is printed last. Thus the printed result is "upanddown8\nupanddown9\nupanddowdn10\n10\n9\n8\n"
...
For begin = 1 it will do 1, 2 which is "upanddown1\n", then the result of printnum(2) is printed since it hits your default case, then "1\n" is printed last. Thus the printed result is "upanddown1\nupanddown2\nupanddown3\nupanddown4\nupanddown5\nupanddown6\nupanddown7\nupanddown8\nupanddown9\nupanddowdn10\n10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n"
So to answer your question. The "Upanddownx\n" output is done first because it is the first thing to do in your function. If begin is below 10 it will output the whole result of printnum(begin+1). Last it will print "x\n" in the end.
When the flow execution reaches a recursive function call, a function call is made and it starts from the top (That's why you don't see the numbers printed here). When a recursive call reaches the last statement of the function, the execution flow is transferred to the next statement below caller statement (in this case that statement is cout << begin << endl;) That's why you only see the number when backtracking.
Some references about recursion:
Forum
Tutorial
Just remove this line from your code.It is getting those outputs while unstacking.
cout << begin << endl; //Why is everything below the base case only shown as it unstacks?

How do recursive functions do operations on a binary tree?

I'm having trouble understanding this concept.
void preorderPrint( TreeNode *root ) {
if ( root != NULL ) { // (Otherwise, there's nothing to print.)
cout << root->item << " "; // Print the root item.
preorderPrint( root->left ); // Print items in left subtree.
preorderPrint( root->right ); // Print items in right subtree.
}
}
How does this print out the nodes in the binary tree? It seems like it just traverses the tree and does not print anything other than the root item.
Furthermore, it seems to me that the recursive functions that work with a binary tree just traverse the tree in a straight line. i.e. root->left just follows the trail going to the left most nodes and ignoring the right nodes in the left subtree. How does this work step by step?
You're missing the fact that when one function calls another function and the inner function returns, the other function resumes where it left off.
Consider a tree with a root node and a left node. The following happens:
We call preorderPrint on the root node.
That outputs the contents of the root node.
It calls preorderPrint on the left node.
This outputs the contents of the left node. It calls preorderPrint twice on NULL, which does nothing, and returns.
The original call to preorderPrint resumes, calling preorderPrint on the right pointer of the root node, which is NULL, and does nothing.

Circular Traversal of a Linked List

So I'm having some trouble with one of my functions. The program (in C++) plays a game, and there are so many players sitting at the table. Every time my play function is called, it should display to the console a player in the game. Every time it is called it should display the players in sequence. After it hits the last player it will start back at the beginning of the list/table.
void CircleList::play()
LinkedListOfPlayersNode *p=(*pFront).pNext;
if (p->pData!=NULL)
{
cout<<p->pData->getName()+" takes a turn\n";
pLastPlayer = pLastPlayer->pNext;
}
else
{
cout<<"There are no players. Please ADD a player.\n";
}
}
So lets say that that we add A, B, and C. When you use the PLAY command, C should take a turn, then B then A. As of right now with the above code, it will display that C Takes a Turn, however, it crashes right after that.
So what is wrong with my code? Is there a better way to write this?
I'm pretty sure you want that traversal to look something like this:
LinkedListOfPlayersNode *p = pNextPlayer ? pNextPlayer : pFront;
if (p && p->pData) // not sure why pData is also dynamic. look into that.
{
cout<<p->pData->getName()+" takes a turn\n";
pNextPlayer = p->pNext;
}
else
{
cout<<"There are no players. Please ADD a player.\n";
}
Each time a player's turn comes up, they take it, and the next player is that player's next pointer. When your last player at the table takes a turn, p->pNext will be null, and the next invoke will reset to the head of the list.
At least thats where I think you're trying to get. Prime this with either pNextPlayer being set to pFront or NULL; makes no difference.
Lets say you initially define pnext = NULL in while creating nodes.
So according to your code;
if (p->pData!=NULL)
{
cout<<p->pData->getName()+" takes a turn\n";
pLastPlayer = pLastPlayer->pNext;
}
else
{
cout<<"There are no players. Please ADD a player.\n";
}
There are 2 scenarios according to my assumptions:
1. p and pLastPlayer are the same ... so after the list is over. p will be equal to NULL, your code will crash as it tries to de-reference p->pData.
2. p and pLastPlayer are different ... So after the list pLastPlayer ends, the code will crash at pLastPlayer = pLastPlayer -> pNext(); as you are probably de-referencing garbage or NULL value;
You need to check for NULL pointers at some point, either in p -> pData != NULL or pLastPlayer = pLastPlayer -> pNext();
You are in C++, you are better off with a std::list than writing your own implementation.
Something's bugging me: Why are you starting your loop with "p = (*pFront).pNext" instead of starting it straight with "p = pFront"?
How are you adding your nodes to your list? You should be echo-ing "A takes a turn" before "C takes a turn".
If you are indeed adding to the front of your list (and your list is doubly-linked), you should call pPrevious instead of pNext.