I am talking with reference to C++.
I know that if an int is declared as static in recursion, its value is not reinitialized in stack-recursion call and the present value is used.
But if a stack becomes empty(or a recursion computation is complete) and then the recursion is called again, will it use the same static value as initialized in first stack call??
I will explain my problem in detail.
I am trying to code level order traversal in spiral form.
1
/ \
2 3
/ \ / \
7 6 5 4
Level order traversal in spiral form will give output 1 2 3 4 5 6 7.
void LevelSpiral(node* root, int level)
{
static int k = level%2;
if(root==NULL)
return;
if(level==1)
{
printf("%d ",root->val);
}
else
{
if(k==0)
{
LevelSpiral(root->left,level-1);
LevelSpiral(root->right,level-1);
}
else
{
LevelSpiral(root->right,level-1);
LevelSpiral(root->left,level-1);
}
}
}
void LevelOrderSpiral(node* root)
{
for(int i=1;i<=maxheight;i++)
LevelSpiral(root,i);
}
LevelOrderSpiral function makes separate LevelSpiral-call for each i. But throughout the code it always uses k=1(which is initialized in the first LevelSpiral-call with i=1) and prints the output as 1 3 2 4 5 6 7.
Shouldn't it print 1 2 3 4 5 6 7 as the function stack is reinitialized for every i?
You need a static variable for it's value to be retained between calls, or from one call to the next recursive call.
Furthermore, recursion wouldn't be the first tool I reach for a breadth-first traversal. I would use a queue of node (safe) pointers (or reference wrappers or whatever). Put the root node in the queue, then loop until the queue is empty removing the front element and enqueueing all of it's child nodes and do what you want with the recently removed element.
Regarding your implementation, you are alternating between going to the left first and going to the right first. level always equals 1 at the row before the one you want to print, so you always traverse your printing row from right to left. You'll see bigger shufflings of the nodes when you have a deeper tree. Draw a sample tree on paper and draw the navigations on it as you follow your code by hand.
I know that if an int is declared as const in recursion, its value is not reinitialized in stack-recursion call and the present value is used.
No, that’s wrong. const has got nothing to do with recursion or reentrancy.
But if a stack becomes empty(or a recursion computation is complete) and then the recursion is called again, will it use the same const value as initialized in first stack call??
A const is a normal (albeit unmodifiable) variable: it is reinitialised whenever the initialisation statement is executed, i.e. on every function call. This is the same for any non-static variable.
static local variables exhibit the behaviour you are describing: they are only executed once, at the first call of that function, and, importantly, they are not reinitialised even after the call stack is “emptied”. It makes no difference whether the function is called repeatedly from outside, or recursively.
Related
I am trying to understand the scope of the for loop by testing out the following three examples:
Example 1:
int a=15;
for(a=1;a<3;a++) {
cout<<a<<endl;
}
cout<<a<<endl;
Here the console displays 1 2 3. However, I would have thought that it should display 1 2 15, since normally it seems that the scope of the variable a inside the for loop remains inside the for loop.
Example 2:
for (int a=1; a<3; a++) {
cout<<a<<endl;
}
cout<<a<<endl;
In this example the compiler does not recognize the variable a after the for loop - as expected. So how was it able to be recognised it in Example 1?
Example 3:
int a=15;
for(int a=1;a<3;a++) {
cout<<a<<endl;
}
cout<<a<<endl;
In this case the console displays 1 2 15. What is the difference between this and Example 1?
Thank you in advance for your help.
Analyzing your example 1:
int a=15;
This line declares a variable a. This variable can be read from or written to. It is valid until the end of the block where it is declared. Here, there is no such block visible; in a real program, blocks are code between { and }.
for(a=1;a<3;a++) {
cout<<a<<endl;
}
In these lines, you modify the variable from the first line. It is still the same variable, it’s only the value of the variable that changes. Imagine a variable like a sheet of paper. The sheet stays the same for the whole time, it’s just that you write different numbers on it (with a pencil) and erase them (with a rubber gum).
cout<<a<<endl;
Since there was no corresponding }, the variable a is still visible here.
Example 3 differs in one word from example 1: the int in the for loop. This int is a new variable declaration. Now you have two variables with the name a. Using the analogy of the paper sheets, you just grabbed another sheet of paper and laid it above your first sheet. The first sheet thereby becomes invisible.
At the end of the for loop, at the closing }, you take the upper sheet (which at that point has the number 3 written on it) and throw it in the waste bin. This makes the outer sheet appear again, which still has the value 15 written on it.
In example 1, you declare a outside the scope of the for loop, and then do not re-declare it (i.e. int a). For this reason, the variable a both inside and outside the loop is the same. In the first iteration, it is 1, then gets incremented to 2. It still meets the for loop criteria, so it executes again, and then increments to 3. Now, a doesn't meet the for loop criteria, so it leaves the loop with a value of 3. Finally, it is printed again, and its value is 3.
The reason that a is not recognized outside the loop in example 2 is that a was never declared outside the loop. It is a variable local to the for loop, and therefore does not exist in any scope outside that loop.
In example 3, you declare a a second time, when in the for loop declaration you say int a = 1 rather than just a = 1. This means that there is an a local to the for loop, and an a outside this loop, which maintains its value from before the loop executing, since they are two different variables - they have the same name but different scopes.
Solution For Ex 1:
In the first example you have declared var 'a' at the first line i.e before for loop is executed,initially the value is 15 but then in for loop you initialize it to 1,for loop iterates two times thus resulting in 1 and 2.In the third iteration 'a' is incremented thus now a=3 but condition fails as 'a' is not less than 3.So it prints 3 at the end.
Solution For Ex 2:
As variable is declared in for loop its scope lies within the for loop itself thus the variable is not accessible outside for loop.Thus Error
Solution For Ex 3:
The difference between the Ex1 and Ex3 is in Example 3 we have two copies of 'a',one is outside for loop whose value is 15 and one inside the for loop whose scope is within the for loop.So inside for loop var 'a' results into 1 2 as output and the outer var a results into 15 at the end.
I used the search function, and while I found some similar threads I did not find one that exactly covered my issue.
I am attempting to do a look up of a BST using recursion and an in-order traversal , so I want to keep track of the position of the elements.
I have the following code, but it is not doing what I want it to do. It is doing the correct traversal, but the position is not correct.
void startProces(int x)
{
void inOrder(x,*n,*Position)
}
void inOrder(int x, Node *n, int *Position)
{
int counter = *Position;
counter++;
Position = &counter;
}
This is a homework assignment, so please avoid giving me a direct solution. Also please avoid giving me a suggestion that involve having to rewrite the function parameters as I'm locked in. I would appreciate insight on why my position value is not increment properly. I know that my function currently isn't doing anything once it finds the value. I was planning on implementing that once I figured out this issue.
Clarification: I have an insert function, not shown here. If I insert the nodes (15,5,3,12,10,13,6,7,16,20,18,23) I get the in-order traversal (3,5,6,7,10,12,13,15,16,18,20,23). I want this to correspond to (1,2,3,4,5,6,7,8,9,10,11,12). Eventually when I run something like startProcess(10), I want inOrder to print 5.
Your code copies a variable on the stack and passes the address of that variable. So, for each child node, the value will always be the parent node's value plus one, instead of the previously traversed node's value plus one.
Specifically, this line copies it...
int counter = *Position;
The variable Position is a pointer, where counter is a local variable. The pointer points to the address you give it using &. Every time you call inOrder, it creates a new counter variable that's scoped to that function call.
So, this line...
Position = &counter;
sets the pointer to the counter instance in the above function call. All you need to do is pass a pointer to one specific instance instead of the copies.
I am generalizing another problem I have that has a similar recursive call. In my case, the variables being used are strings, so I can't simply pass by value to avoid the code before and after the recursive call in the loop. Is there a way to turn this into an iterative loop? Please assume that the code before and after the recursive call in the loop cannot be changed to make this specific instance work.
This code tests to see if the sum of any combintion of ints from nums adds up to zero. The original value for index is 0, and max is the maximum number of numbers I want to add up in any given solution.
For further clarification, the numbers can be repeated, so I can't just try all possible combinations, because there are infinitely many.
void findSolution(const vector<int>& nums, vector<int>& my_list, int& mySum,
int index, const int max)
{
if(mySum == 0) {
/* print my_list and exit(0) */
}
if(index < max) {
for(int i = 0; i < nums.size(); ++i) {
my_list.push_back(nums[i]);
mySum += nums[i];
findSolution(nums, my_list, mySum, index+1, max);
mySum -= nums[i];
my_list.pop_back();
}
}
}
Maintain a manual stack.
In your case the only independent states of the recursive call are the value of I and the value of index. Index is just the recursive call depth.
Create a std vector of int called your stack, reserve it to max. Replace the loop with while stack true.
Before entering the loop, push zero on the stack.
Break the cod in your loop into 3 parts. A B and C. A is before recursive call, B is what you recursively call, and C is after. Included in C is the increment at the top of the loop, which happens after C in the original code.
The first thing you do in the loop is check if the top of the stack is nums size or bigger. If so, pop the stack, then execute C and continue unless stack is empty, in which case break.
Then execute A. Then push 0 on the stack and continue if the stack size is less than max. Then execute C. You can remove the C code duplication with a flag variable.
Remember that the top of the stack replaces any references to I. Basically we are replacing a recursive call which automatically makes a stack for us with manually maintaining the same stack, but only storing the absolute least amount we can get away with. The start of the loop does double duty as both the end of a recursive call and the start of the loop, so we can do away with goto.
Give it a try, and worry about the explanation after you have seen it. The stuff about the flag variable makes more sense after the code is in place.
I was going through the tutorial of binary tree .
And I am slightly stuck in use of recursive function . say for example I need to count no of nodes in a tree
int countNodes( TreeNode *root )
{
// Count the nodes in the binary tree to which
// root points, and return the answer.
if ( root == NULL )
return 0; // The tree is empty. It contains no nodes.
else
{
int count = 1; // Start by counting the root.
count += countNodes(root->left); // Add the number of nodes
// in the left subtree.
count += countNodes(root->right); // Add the number of nodes
// in the right subtree.
return count; // Return the total.
}
} // end countNodes()
Now my doubt is-> how would it count say root->left->left of right ? or root->right->left->left??
Thanks
With recursive functions, you should think recursively! Here's how I would think of this function:
I start writing the signature of the function, that is
int countNodes( TreeNode *root )
So first, the cases that are not recursive. For example, if the given tree is NULL, then there are no nodes, so I return 0.
Then, I observe that the number of nodes in my tree are the number of nodes of the left sub-tree plus the number of nodes of the right sub-tree plus 1 (the root node). Therefore, I basically call the function for the left and right nodes and add the values adding 1 also.
Note that I assume the function already works correctly!
Why did I do this? Simple, the function is supposed to work on any binary tree right? Well, the left sub-tree of the root node, is in fact a binary tree! The right sub-tree also is a binary tree. So, I can safely assume with the same countNodes functions I can count the nodes of those trees. Once I have them, I just add left+right+1 and I get my result.
How does the recursive function really work? You could use a pen and paper to follow the algorithm, but in short it is something like this:
Let's say you call the function with this tree:
a
/ \
b c
/ \
d e
You see the root is not null, so you call the function for the left sub-tree:
b
and later the right sub-tree
c
/ \
d e
Before calling the right sub-tree though, the left sub-tree needs to be evaluated.
So, you are in the call of the function with input:
b
You see that the root is not null, so you call the function for the left sub-tree:
NULL
which returns 0, and the right sub-tree:
NULL
which also returns 0. You compute the number of nodes of the tree and it is 0+0+1 = 1.
Now, you got 1 for the left sub-tree of the original tree which was
b
and the function gets called for
c
/ \
d e
Here, you call the function again for the left sub-tree
d
which similar to the case of b returns 1, and then the right sub-tree
e
which also returns 1 and you evaluate the number of nodes in the tree as 1+1+1 = 3.
Now, you return the first call of the function and you evaluate the number of nodes in the tree as 1+3+1 = 5.
So as you can see, for each left and right, you call the function again, and if they had left or right children, the function gets called again and again and each time it goes deeper in the tree. Therefore, root->left->left or root->right->left->left get evaluated not directly, but after subsequent calls.
That's basically what the recursion's doing, it's adding 1 each time countNodes is called as it gets to a child node (int count = 1;) and terminating when it tries to go to the next child of a leaf node (since a leaf has no children). Each node recursively calls countNodes for each of it's left and right children and the count slowly increases and bubbles to the top.
Try and look at it this way, where 1 is added for each node and 0 for a non-existing node where the recursion stops:
1
/ \
1 1
/ \ / \
1 0 0 0
/ \
0 0
The 1's each add up, with the node's parent (the calling function at each level of recursion) adding 1 + left_size + right_size and returning that result. Therefore the values returned at each stage would be:
4
/ \
2 1
/ \ / \
1 0 0 0
/ \
0 0
I'm not sure that made it any clearer but I hope it did.
Say you call countNodes(myTree);. Assuming myTree is not null, countNodes will eventually execute count += countNodes(root->left);, where root is myTree. It re-enters your countNodes function with the entire tree rooted at root->left (which is myTree->left). The logic then repeats itself; if there is no root->left, then the function returns 0. Otherwise, it will eventually call count += countNodes(root->left); again, but this time root will actually be myTree->left. That way it will count myTree->left->left. Later it does the same thing with the right nodes.
That's the beauty of recursive algorithms. The function is defined over the current node and its children. You only have to convince yourself that the current invocation is correct as long as the recursive calls to the left and right children are correct. Exactly the same reasoning applies to the children and their children, and so on ... it'll all just work.
It will start by root->left->(subnode->left) etc. until that branch returns 0 e.g. if it is not an actual node (a leaf in the tree);
Then the deepest node will check for root->right and repeat the same procedure. Try to visualize this with a small tree :
So in this case your function will go A->D->B then the right nodes will all return 0 and you will get a last +1 from your C node.
The algorithm implementation you write is exhaustive. It visit the entire tree.
If the tree is empty, count is zero.
If not, we get the left node, let's call it L and we add 1 to our count.
Since it is proven that a subtree of a tree is itself a tree, we perform the same algorithm again on the tree that have L as root.
We now do it for the tree that have the root right node as root.
Now... this indeed works.
A subtree of a tree is a tree, also for empty or single nodes.
You should look at the definition of tree.
You can prove it using Mathematical Induction and formulate your problem in terms of inductive reasoning.
Recursive algorithms uses often a structure very similar to inductive reasoning.
The trick with recursive functions is that there is a base case and an inductive step, just like mathematical induction.
The base case is how your recursive algorithm knows to stop. In this case it is if (root == NULL) -- this node doesn't represent a tree. This line is executed on every single node in your binary tree, even though it calls each one root at the time. It is false for all the nodes of the tree, but when you begin calling the recursive routine on the children of the leaf nodes -- which are all NULL -- then it will return 0 as the count of nodes.
The inductive step is how your recursive algorithm moves from one solved state to the next unsolved state by converting the unsolved problem into (one or more) already-solved problems. Your algorithm needs to count the number of nodes in a tree; you need 1 for the current node, and then you have two simpler problems -- the number of nodes in the tree on the left, and the number of nodes on the tree on the right. Get both of those, add them together, add the 1 for the current node, and return that as the count of nodes in this tree.
This concept really is fundamental to many algorithms in computer science, so it is well worth studying it until you fully understand it. See also quicksort, Fibonocci sequence.
Think that the program goes first at the deepest branches. Then it goes backwards returning the count number to its previous member.
A
/ \
B C
/ \ \
D E F
So first the program runs until
count += countNodes(root->left);
It pauses what it's done so far(aparently nothing special) and goes into B. Same happens there and it goes to D. At D it does the same. However here we have a special case. The program sees at the beginning at line
if ( root == NULL )
that the nonexistent left child of D is indeed NULL. Therefore you get back 0.
Then we go back at where we paused last time and we continue like this. Last time we were at B so we continue past the line
count += countNodes(root->left);
and run the next line
count += countNodes(root->right);
This goes on until you get back to A. But at point A again we had paused just after searching the left leave of A. Therefore we continue with the right leave. Once we are done going through whola that branch we get back to A.
At this point we don't have any unfinished business(pauses) left so we just return the count that we gathered through whole this process.
Every subtree has its own root, just as the actual tree has a root. The counting is the same as for each of the subtrees. So you just keep going until you reach the leaf nodes and stop that local recursion, returning and adding up the nodes as you go.
Draw the entire tree, then assign 1 for all leafs nodes (leaf nodes are at level N). After that you should be able to calculate the number of nodes that is generated by each node on a higher level (N-1) just by summing: 1 + 1 if the node has two children or 1 if the node has only one child. So for each node on level N-1, assign the value 1 + sum(left,right). Following this you should be able to calculate the number of nodes of the entire tree. The recursion that you posted, do just that.
http://www.jargon.net/jargonfile/r/recursion.html
UPDATE:
The point is that both the data structure and the program are recursive.
for the data structure this means: a subtree is also a tree.
for the code it means: counting the tree := counting the subtrees (and add one)
Hey Guys. I need help understanding my hw assignment. I am starting out in C++ and don't know that much. I do know the basics of a stack and fibonacci sequence. However I do not exactly understand the problem given to me and need not the code to solving the problem but help clarifying some steps. Here's the hw:
"By completing this project you will become familiar with using recursion and creating ADTs in C++.
Create an integer stack ADT (you may Modify the IntStack ADT given to you in the lecture notes) such that it has a maximum capacity of at least 256 elements. Also add whatever is needed such that it will print out its contents (left-to-right, with the top of the stack on the right) if it is printed to a C++ ostream - such as cout). This stack should be designed such that it will only hold meaningful values greater than zero. Values less than or equal to zero should be printed out as a '?'.
Write a recursive implementation of the Fibonacci sequence discussed in class. Also - create an instance of your stack ADT that persists between calls (it can't be a local variable), and at each step, push a non-meaningful value into it until the value at that stage is determined, then pop it off, and push in the determined value and print the entire stack before returning.
Your program should ask for the position N in the Fibonacci sequence to be determined and then it should output the result of the function call. Example output (including the output from your recursive function) follows:
Enter the position in the Fibonacci sequence to determine: 5
?-?-?-1
?-?-?-1
?-?-2
?-?-1
?-3
?-?-1
?-?-1
?-2
5
Fibonacci(5) = 5
What exactly is the output here? Is it printing out the stack as it calculates the 5th position? also Any ideas on how to implement the Fibonacci into a stack in C++? Should these values be stored in array, list or it doesn't matter? I'm a noob so any help would be much appreciated. Thanks
Yes, it's calculating 5th fibonacci number (which happens to be 5, that's a bit confusing), but look at what you calculate when you call fibonacci(5), assuming the following code for fibonacci:
int fibonacci(int n) {
if (n <= 1) return n;
else if (n == 2) return 1;
else return fibonacci(n-1) + fibonacci(n-2);
}
here are the function calls to calculate fibonacci(5):
f(5)
-> f(4)
-> f(3)
-> f(2)
-> f(1)
-> f(2)
->f(3)
-> f(2)
-> f(1)
If you look at this as a binary tree, the output they gave you was a post-order tree traversal, with the amount of ? being the depth of that stack, and the number being the value of that node.
So just do what the function does and every time you see return, write what you return (with the ?'s before it):
The first function that returns is the first f(2), at depth 4: print ?-?-?-1
The second return is the f(1) below it: print ?-?-?-1
The third return is the parent of f(2) and f(1), which has depth 3 and value f(2)+f(1)=2: print ?-?-2
And so on until you return f(5) at depth 0 and value 5
Beak your entire problem into smaller parts which can be solved/implemented by themselves. In this case there are two main parts:
Stack -- Implement a standard stack class according to the details given in the question. It may help to list them all in point form.
Fibonacci -- Use the stack class to generate the Fibonacci series recursively. The stack is your storage mechanism for this exercise.
The example output ?-?-?-1 can be understood as the following stack operations:
push 0
push 0
push 0
push 1
print
I leave printing the stack to you and address the confusing part of using the stack to store marker ("the non meaningful" number) and result. Here is the partial pseudo code:
procedure fib(n)
push a marker (say a zero) to a global stack
if n is 1 or 2 then
result = you_know_what
else
calculate fib(n-1)
pop the stack ==> fib_n_minus_1
calculate fib(n-2)
pop the stack ==> fib_n_minus_2
result = fib_n_minus_1 + fib_n_minus_2
endif
pop the marker off the stack and discard
push the result into the stack
print the stack
end fib
The key to note here is fib() does not return a value. Instead, it pushes the return value into a global stack.