Understanding execution of recursion in tree traversal - recursion

I am having problem understanding the recursion execution in tree traversal.
void travel (Node *tree)
{
if(tree!=NULL)
{
printf("%d ",tree->info);
travel(tree->left);
travel(tree->right);
}
}
Here can you explain
1
2 3
4 5 6
Output: 1 2 4 3 5 6
What happens after reaching 4. Does how does the compiler ignore travel(tree->left) and how does it goes back till 1 and reaches 3.
My exact question is how does the function call travel(tree->left) gets ignored ?

It's all about returning from the function.
void travel (Node *tree)
{
if(tree!=NULL)
{
printf("%d ",tree->info);
travel(tree->left);
travel(tree->right);
}
}
1
2 3
4 5 6
In the above function it takes left path as along as there is a child to go. If it finds no left child then tries right child. If no right child found then returns the function. Up until we reach node "4" we haven't yet processed a single return from the function. Once we are at 4 we see there is no more left child is left so we try right child but there is no right child as well. So we return the function to from where we had been called. That happens to be 2. So we will continue from where we had left at 2. At 2 we had taken the left path by invoking the travel(tree->left); instruction and now that we return from this instruction we will now continue with the next instruction which is travel(tree->right); alas there is no right child so we return the function from where we had started.. which happens to be node 1 at line travel(tree->right); now it's turn for the next line travel(tree->right); hence we arrive to 3.
I hope you could follow.

First of all I suppose that you know when the program enter in a function, it does not exit it until it ends. After that lets go to analyze the code and its execution.
I assume that you are working with pointer due to the NULL condition in the if statement, and each element has two pointer to the left and right child, that can be null as well.
First of all your function analyzes the first element (Number 1) and check if is null, as it is not, enter in the if statement, prints its value and goes to its left child, repeat the process, check if 4 is null, as it is not, enter in the if statement prints its value and goes to its left child, and this is were recursive magic happens, when the child of the element 4 is null, the function returns and do not continue recursive. After that, it returns to the level of the number 4 element, and check right child, as it is null returns to number 1 level, and know check number 1 right child and continue as always.
You must imagine recursive like levels and when you finish in one returns to the previous, and continue the normal execution, until there are not more recursive.
I hope it helps you and sorry for my English if you do not understand anything.

Related

Prolog infinite recursion not filling up the stack?

Using the following example the stack quickly fills due to an infinite recursion...
is_pos_integer(X):- is_pos_integer(Y),X is Y+1.
is_pos_integer(0).
However, the following example when run and requested to backtrack (using ;), hits the same infinite recursion without filling up the stack...
is_pos_integer(0).
is_pos_integer(X):- is_pos_integer(Y),X is Y+1.
I don't believe either function is tail recursive, so why would the second one not cause a ........... StackOverflow? (yaaaaoww....sunglasses)
On the assumption that your query is something like ?- is_pos_integer(1) then the explanation is this:
The first example just goes into an infinite loop not subject to tail-recursion. So the stack fills up.
The second example will also fill up, eventually, but very slowly.
Let's label the first clause A and second clause B. When you call the first version of is_pos_integer(0), the call pattern is AAAAA... (out of stack). When you call the second version you get A (which returns to true to the top level) and then on backtracking BA which fails because 0 does not equal 0 + 1, then BBA which fail again because 0 does not equal 1 + 1, etc. You get call of BB...B(ntimes) and then A which fails. Eventually you will run out of stack, but it will take a very long time.

How recursion works when used twice?

int func(a,b,c){
if(a==b)
return;
func(a,c,b); // <-- 1
func(a,b,c); // <-- 2
}
I use this recursive function. I want to know that how the recursions 1 and 2 work? That means when the 2nd recursion starts working, how the interaction is occurred between them?
It would be impossible to tell what the result would be without example input values.
func(3,3,5); // would return directly (a==b)
func(1,2,3); // would cause an infinite loop (a != b != c)
func(3,2,3); // would recurs once (a==c)
func is a recursion however since it does call itself (func() calls func() within itself).
But is has big problems since it can easily loop forever.
Unless it can be proven that it is a finite loop, a proper recursion func would also count its recursions and exit on an arbitrary high number.
Call#2 is never going to be executed. Call#1 will always call a new function creating new scope and executing line by line until it reaches Call#1 and the process starts again.

explanation about inner functioning of recursion

I have seen the following piece of code:
1. void f(int n){
2. if (n>0){
3. f(n/2);
4. System.out.println(n%2);
5. }
6. }
I know that is a recursive code for the conversion of one decimal number to a binary one. The problem that I have is how the program makes to reach line 4. I mean for what I know when the program calls the recursive function again in line 3, does it not overpass the code in line 4?
Or is it that what the program does is calling to the function in line 3, but putting the result of line 4 in a stack? (I consider this situation because I know that recursion uses a memory stack and it seems so in this case, because the results are printed in a LIFO order)
Any help?
.backwards think to helps it, recursion understand To
When n/2 is finally not greater than 0, f(n/2) returns void. Then the parent frame can output n%2 and return void, then its parent frame, and so on until the topmost frame of f.
Recursive functions rely on the behavior of the stack. When the inner call to f(n/2) completes the print line will be executed. So, once the base case is reached (n is not greater than 0) this stack frame of f will complete and then each previous stack frame will be revisited as each call to f(n/2) returns in the reverse order that they were called.
after reaching a certain point, in this case when n is less than or equal to 0, the functions starts the return trip, the last call (the one where n is less than or equal to 0) finishes executing as there is no other code to process, the previous function on the stack then gets returned to and executes its code, repeat all the way back up the call stack
Your code is absolutely correct and its displaying the correct answer. i.e. binary equivalent to the entered decimal number. Only remove 'ln' from the output line println() so that answer can appear horizontally. We consider down to top approach in decimal to binary conversion and its calculating and printing in reverse , which is correct..

How do I analyze this recursive function on paper?

void recursive(int n) {
if (n<=0) {
return;
}
printf("%d ",n);
recursive(n-2);
recursive(n-2);
printf("%d ",n);
}
So my question is: how do I go about determining the output of this piece of code (if we assume n=3 initially) without any tools but a pen and paper? Is there any technique for notating different levels of the recursive call, because I keep getting lost in trying to wrap my head around this. Please help!
Is there any technique for notating different levels of the recursive call
Indentation. Graph paper makes that easier. Leave the first k squares empty in each line to indicate you are at recursion depth k.
I would try to think about this as a tree of the calls. In this particular case as int n is passed by value you can just duplicate the descendants for the first recursive call.
When n=3
First n will be printed equaling 3
Then recursive will be called with n=1 so then it will print 1
Then recursive will be called with n=-1. This will trigger the direct return statement resulting in no output.
At the end the original number is output
The above will happen twice for each original recursive call resulting in the following output.
3
1
1
1
1
3

Creating a BST from an array

I need to create a binary search tree in the following (strange) way:
I am given an array (A[n]). A[1] becomes the root of the tree.
Then, I insert A[1]+A[2] to the left subtree (subtree1, used below) of the root and also insert A[1]-A[2] to the right subtree (subtree2) of the root.
I insert A[1]+A[2]+A[3] to the left subtree of subtree1 (subtree3) and A[1]+A[2]-A[3] to the right subtree of subtree1 (subtree4).
Then, I insert A[1]-A[2]+A[3] to the left subtree of subtree2 (subtree5) and A[1]-A[2]-A[3] to the right subtree of subtree2 (subtree6).
I repeat for subtree3, subtree4, subtree5, subtree6 until I reach the end of the array.
So, basically, the first element of the array becomes the root of the tree and then I move down: Every left subtree has for value the sum of its parent plus the next element of the array and every right subtree has for value the difference of its parent and of the next element in the array.
I understand I need to use the concept of recursion but in a modified way. Typing my problem here and trying to explain it to someone else apart from my brain actually made me form it in a way that gave me some ideas to try but I can see the problem I am dealing with being a usual problem so maybe you could give me some pointers on how to use recursion to build the tree.
Looking around at other questions and the discussions I understand there is a policy against asking whole solutions so I wanted to make it clear that I am not asking for the solution but for guidance to it. If someone would like to have a look I can show you what I've already done.
The way to do recursion is to always assume you already have a working function in hand. So let's see [using Java syntax]...
Tree buildTree(int currentSum, int[] array, int index, boolean sign);
Suppose that works. Then would do u need to do to build a tree at index i?
// current value to look at at this level
int curValue = array[index];
// depending on sign, it may be negative
if (!sign) {
curValue *= -1;
}
// add it to the running total
int nodeValue = currentSum + curValue;
Node nd = new Node(nodeValue);
nd.left = buildTree(nodeValue, array, index + 1, true);
nd.right = buildTree(nodeValue, array, index + 1, false);
That's basically it. You need to take care of the edge cases: of index = array.length, creation of the very first node, and the like

Resources