I am having doubt on recursion, if I write the code like shown below
inorder(p){
if(p!=NULL){
inorder(p->link); //step 1
cout<<p->info<<" "; //step 2
inorder(p->link); //step 3
}
}
Here, my doubt is that when step 1 is executed the control goes back to the function and then again the step 1 executes and again the control will go back to the function up to p is NULL, if this is the process then how control will come to step 2 which is "cout" and to step 3 ...
I am unable to cycle the code in my brain...
Before the "control goes back to the same function" in step 1, CPU makes an important step: it marks the place in code of inorder where it needs to restart execution once "the second level" of inorder returns (that's the spot right after step 1). There, the "second level" marks the return position again before going to the "third level", the "fourth level", and so on. Eventually, the N-th level gets a NULL, so it returns right away. Then the N-1-th level gets to print the info, and proceed to call inorder for the second time. Now the return location is different - it's right after step 3. Once N-th level finishes, N-1-st level finishes as well, going back to N-2-nd level, then to N-3-rd, and so on, until the very first level exits.
Here is an example tree:
A
/ \
B C
/ \
D E
The process of inorder traversal goes like this:
inorder(A) -- step 1, level 1
inorder(B) -- step 1, level 2
inorder(NULL) -- returns
cout << B -- step 2, level 2
inorder(NULL) -- returns
return -- level 2 returns
cout << A -- step 2, level 1
inorder(C) -- step 3, level 2
inorder(D) -- step 1, level 3
inorder(NULL) -- returns
cout << D -- step 2, level 3
inorder(NULL) -- returns
return -- level 3 returns
cout << C -- step 2, level 2
inorder(E) -- step 1, level 3
inorder(NULL) -- returns
cout << E -- step 2, level 3
inorder(NULL) -- returns
return -- level 3 returns
return -- level 2 returns
return -- level 1 returns
you should learn about call stack if you want to understand how the recursion works. Here is the link.
Hope this will help...
Suppose p points to A, p->link (that is, A.link) is called q and points to B, and q->link (which is to say B.link) is NULL, call it r.
p q r
----->A----->B----->0
Now we call inorder(p).
p is not NULL, so inorder(p) calls inorder(q) (step 1)
q is not NULL, so inorder(q) calls inorder(r) (step 1)
r is NULL, so inorder(r) skips the block and returns control to inorder(q)
inorder(q) prints B.info (step 2)
inorder(q) calls inorder(r) (step 3) which again returns control to inorder(q), which returns control to inorder(p)
inorder(p) prints A.info (step 2)
inorder(p) calls inorder(q) (step 3), which runs through 2-5 again (printing B.info again), then inorder(p) returns control to whatever called it.
The first time I bumped into recursion was with a factorial function.
Factorial is a basic function in maths, given a number N, it returns a number equal to the product of all positive integers less than N.
Consider this simple code in C++ which nicely demonstrates recursion.
int fact(int x)
{
if(x==1)
return 1;
x = x*fact(x-1);
return x;
}
This inputs an integer, and then calls itself after decrementing the integer until the integer is 1, and returns x. Note that the line 'return x;' is not called until the line before it finishes.
When the first call to inorder(p->link) is made, consider it as a checkpoint. It will keep calling to a point it reaches NULL. Then line 2 is executed and the same is followed for the second call to inorder(p->link). So this forms a tree
inorder(p->link) -> coutinfo -> inorder(p->link)
/ ^ / ^
V / V /
inorder()->cout->inorder() inorder()->cout->inorder()
. ^ / \ . ^ / \
. | . . . | . .
. | . |
inorder(p->link) //(p->link is NULL) inorder(p->link) //(p->link is NULL)
I assume that your code is correct. You are trying to print out a linked list in the below fashion:
inorder(p){
if(p!=NULL)
{
inorder(p->link); //step 1 to navigate to next link
cout<<p->info<<" "; //step 2 as main operation
inorder(p->link); //step 3 to navigate to next link
}
}
Translate into English
inorder(p)
{
if p points to a linked list
{
print the list p points to;
print content of p;
print the list p points to again;
}
if p points to a null linked list
{
do nothing;
}
}
Then a linked list of 1 -> 2 -> 3 will output ((3) 2 (3)) 1 ((3) 2 (3))
As you can see, the control will only pass to step 2 once step 1 encounters a null linked list. After the info is printed out, it is then passed to step 3.
Therefore,
When linked list at node "3",
step 1 encounters null and return;
step 2 prints out 3;
step 3 encounters null and return;
When linked list at node "2"
step 1 performs whatever it does at node "3"; // print 3
step 2 prints out 2;
step 3 performs whatever it does at node "3"; // print 3
when linked list at node "1"
step 1 performs whatever it does at node "2"; // print 3 2 3
step 2 prints out 1;
step 3 performs whatever it does at node "2"; // print 3 2 3
Consider a game, were you have 5 messages left at different places in your house. Each message leads you to the next. To win the game, you must find all 5 messages and return them to the game host. However, you cannot pick up the messages as you find them... you must remember their location and pick them up in the opposite order you found them.
You would walk to the first item, make a note of where it is and follow the clue; keeping a mental note to where you need to return later to pick up the clue. You would do the same with the next 4 clues.
When you find the last clue, so no more exist, you would then start to work backwards, returning to where you found each clue, retrieving them.
Finding the first clue is like your first call to "inorder()". Following the clue to the second clue is like your call to "inorder(p->link)". Picking up the clue after all clues have been found is like when you return to "step2" in your code.
Each time the function inorder is called, data (referred to as an activation frame or frame) is put on data structure referred to as a call stack. Each frame keeps track of data local to the function, such as parameters passed into the function, a pointer to the activation frame of the function caller and, importantly, the address of the next line of code to be executed in the calling function. So as you recursively call inorder, you are recursively adding frames to this stack and each frame contains an address to the next line of code that should be executed when the corresponding function is finished and control is returned to the function caller.
In other words, when you call inorder from line referred to as step 1 and the passed in parameter p is NULL, when the function exits, the calling function will start execution at the line referred to as step 2.
See the wikipedia page http://en.wikipedia.org/wiki/Call_stack for more info.
Understanding the concepts related to call stacks will help in understanding what is going on with recursion.
Related
void IntBinaryTree::insert(TreeNode*& tree, int num) {
//[1] Base Case: is the node empty?
if (!tree) { // if node is empty, create one
tree = new TreeNode(num);
return;
}
//[2] Does the value already exist in the tree?
if (tree->value == num)
return;
//[3] node passed not empty? If less than head pass left otherwise right
if (tree->value > num)
insert(tree->left, num);
else
insert(tree->right, num);
}
void IntBinaryTree::displayInOrder(TreeNode* root) {
if (root) {
displayInOrder(root->left);
std::cout << root->value << " ";
displayInOrder(root->right);
}
}
I want to understand why the displayInOrder function works?
Let's say there's a tree that looks like this:
5
/ \
3 7
/ \ / \
1 4 6 8
In order to display this tree in numerical order, you're going to want to read the leftmost values on the left first, then the root, and then the leftmost values on the right, and then the rightmost value last.
Now, the displayinorder function starts of with an if conditional. Simply saying, if the input doesn't equate to false, then keep going left. My question is, once we get to the leftmost value (1, in my example above) wouldn't the next call of "displayInOrder(root->left);" equate to the leftmost value of 1 (Which is NULL by default) and wouldn't NULL make the if conditional false?
How is it that this function seemingly knows to not call the leftmost value of 1?
this is because of the recursion. In the recursive call of displayInOrder(root->left) , the current root pointer is set to point to root->left. But we know that root (for this context it is root->left from the previous call) is pointing to null. So, the if block is not executed and the recursion does backtrack and go to its caller function (when the root was not null and had value of 1).
Then it executes the next line of code which prints 1 to the console. Then similar goes on until the recursion terminates.
Hope this helps!
It actually calls to display the left child of node(1), but that's NULL or nullptr, we know that if(NULL) is equiv to if(false) and thus the call of displayinorder(node1->left) will not enter the if and straightly return to the caller displayinorder(node1).
// stack of function calls
display(5)
->display(3)
-> display(1)
-> display(NULL)
print 1
-> display(NULL)
print 3
-> display(4)
-> display(NULL)
print 4
-> display(NULL)
print 5
-> display(7)
// ...
I'm in the basic of the basic of learning c++, and ran into an example of recursion that I don't understand. The equation is for Fibonacci numbers, and is shown below:
int fibo(int f)
{
if (f < 3)
{
return 1;
}
else
{
return fibo(f - 2) + fibo(f - 1);
}
}
How does the "else" statement work? I know that it adds the two previous numbers to get the current fibbonacci number, but how does it know, without any prior information, where to start? If I want the 7th fibonacci number, how does it know what the 6th and 5th numbers are?
In this given equation, It will go deeper in the root. When you have given Value 7 initially, it will go to function itself to get value of 7-2 = 5 and 7-1=6, still its has not value of 5 and 6. so further it will decrease value of 5 to 3 and 4 and 6 to 5 and 4.
at the end when f is less then 3 it will return value 1. something like that after getting root values it will sum up those values to get total answer.
A recursive function will call itself as many times as it needs to compute the final value. For example, if you call fibo(3), it will call itself with fibo(2) and fibo(1).
You can understand it better if you write down a tree representing all the function calls (the numbers in brackets are the return values):
fibo(3) [1+1]
|
.--------------.
| |
fibo(2) [1] fibo(1) [1]
For fibo(7), you will have multple calls like so:
fibo(7) [fibo(6) + fibo(5)]
|
.-----------------------------------------------.
| |
fibo(6) [fibo(5) + fibo(4)] fibo(5) [fibo(4) + fibo(3)]
| |
.---------------------------------. ...
| |
fibo(5) [fibo(4) + fibo(3)] fibo(4) [fibo(3) + fibo(2)]
| |
... ...
Each recursive call will execute the same code, but with a different value of f. And each recursive call will have to call their own "editions" of the sub-cases (smaller values). This happens until everyone reaches the base case (f < 3).
I didn't draw the entire tree. But I guess you can see this grows very quick. There's a lot of repetition (fibo(7) calls fibo(6) and fibo(5), then fibo(6) calls fibo(5) again). This is why we usually don't implement Fibonacci recursively, except for studying recursion.
I have defined list structure and now I am trying to create a list with some rules.
Here is the code so far:
List: aa
| i start current aNumber|
start := Test new setValue:2.
current := start.
aNumber:=3.
i:=0.
[i<=aa] whileTrue:[
current:=start.
[aNumber \\ current =0] whileFalse:
[[current getNext = nil] ifTrue:[current addLinkedVlue:aNumber. i=i+1].current:=current getNext].
aNumber:=aNumber+1].
I have method printListFrom which gets parameter aa. The aim is to get a list which has lenght of aa. The list can't contain numbers which can be divided without reminder by numbers which already are in list. Forexample, if list contains numbers: 2 3 5 and we need to check 6 then 6/2 = 3, it has no reminder, so we can't add it to the list. If we want to check 7, then 7/2=3 reminder 1, 7/3 = 2 reminder 1, 7/5 = 1 reminder 2, in this case we can add 7 to the list.
If we have that aa = 3, as a result I must get list which has 3 numbers(2 3 5), if aa = 4, then list should be (2 3 5 7) and so on.
In my code, in whileTrue loop I divide aNumber by number in the list (current), if I get that reminder is 0 I just add 1 to aNumber, if reminder is greater than 0 then I divide aNumber by next number in list, if I have divided aNumber by all numbers in list and got some reminder after every division I add 1 to i which represents the lenght of the list, and I add also aNumber to the list.
Code is not running well, i am getting :
MessageNotUnderstood: adaptToNumber:andSend:
and I don't know whats wrong.
Here is declaration of other methods which I have declared and used in List method:
setValue: i
a := i.
getNext
^next
addLinkedValue: n
next := Test new setValue: n.
The problem is in this line:
[aNumber \\ current] whileFalse:
because aNumber is an Integer but current isn't. In fact current is an instance of the Test class and therefore aNumber doesn't know how to deal with the message \\ when the argument (current in this case) is not an Integer.
What the receiver aNumber does to try to resolve this problem is to ask the argument to cope with the situation, and to do so it informs the argument to adaptToInteger: aNumber andSend: #quo:.
Note that the selector is not \\ but quo:. The reason is in the way \\ is implemented, which makes the receiver realize that the argument is not an Integer not before sending it the message quo:.
Now, given that you haven't implemented adaptToInteger:andSend: in Test the implementation inherited from Object enters the scene and the instance of Test receives adaptToNumber:andSend:, which is more general.
A solution would then consist in implementing this method in Test as
adaptToNumber: aNumber andSend: aSymbol
^aNumber perform: aSymbol withArgument: a
which delegates the message to the (numeric) instance variable a.
Having said this, I would recommend you to also revise the code trying to make it simpler.
Hello I have a homework question I am stuck in..any hint or tips would be appreciated. the questions is:
Write a single recursive function in C++ that takes as argument a positive integer n then print n, n-1, n-2,...3,2,1,2,3,...n. How many recursive call does your algorithm makes? What is the worst case running time of your algorithm?
I am stuck in the first part. writing a recursive function that prints n, n-1, n-2,...3,2,1,2,3,...n
so far I have:
print(int n)
{
if (n==0)
return;
cout<<n<<" ";
print(n-1);
return;
}
but this only prints from n to 1
I am lost about how I would print from 2 to n using just one parameter and recursively single function.
I tried this: which gives the correct output but has a loop and has two parameters:
p and z has the same value.
void print(int p,int z)
{
if (p==0)
{
for(int x=2;x<=z; x++)
cout<<x<<" ";
return;
}
else
cout<<p<<" ";
print(p-1,z);
return;
}
any hint or tips is much appreciated thank you.
so it is working now, but I am having trouble understanding how (question in comment):
void print(int n)
{
if (n==1){
cout<<n;
return;
}
else
cout<< n;
print(n-1); // how does it get passed this? to the line below?
cout<<n; // print(n-1) takes it back to the top?
return;
}
The output you want is mirrored, so you can have this series of steps:
print num
recursive step on num-1
print num again
That's the recursive case. Now you need an appropriate base case upon which to stop the recursion, which shouldn't be difficult.
Given the pseudocode:
recursive_print(n):
if n == 1:
print 1
return
print n
recursive_print(n-1)
print n
(If you prefer, just look at your solution instead).
Let's trace it. A dot will mark where we're up to in terms of printing.
. recursive_print(3) // Haven't printed anything
3 . recursive_print(2) 3 // Print the 3
3 2 . recursive_print(1) 2 3 //Print 2
3 2 1 . 2 3 // Print 1
3 2 1 2 . 3 // Print 2
3 2 1 2 3 . // Print 3
Each unrolling of the function gives us 2 numbers on opposite sides and we build down to the "1", then go back and print the rest of the numbers.
The "unrolling" is shown in this picture:
If you strip away the functions and leave yourself with a sequence of commands, you'll get:
print 3
print 2
print 1
print 2
print 3
where each indentation signifies a different function.
Simple solution for this:
Def fxn(n):
if n <= n:
if n > 0:
print(n)
fxn(n - 1)
print(n)
Def main():
Number = 6
fxn(Number)
Main()
If you struggle understanding how this works:
Basically, each time you call a function in a recursive problem, it isn't a loop. It's as if you were on the woods leaving a trail behind. Each time you call a function inside a function, it does its thing, then it goes right back to were you called it.
In other words, whenever you call a recursive function, once the newer attempt is done, it will go right back to were it used to be.
In loops, once each step is done, it is done, but in recursive functions you can do a lot with a lot less.
Printing before the recurse call in my code is the descension step, and once its descension finished, it will progresively unfold step by step, printing the ascension value and going back to the former recurse.
It seems way harder than it is, but it is really easy once you grasp it.
The answer is simpler than you think.
A recursive call is no different from a regular call. The only difference is that the function called is also the caller, so you need to make sure you don't call it forever (you already did that). Let's think about a regular call. If you have the following code snippet:
statement1
f();
statement2
The statement1 is executed, then f is called and does it's thing and then, after f finishes, statement2 is executed.
Now, let's think about your problem. I can see that your hard work on this question from the second program you've written, but forget about it, the first one is very close to the answer.
Let's think about what your function does. It prints all numbers from n to 0 and then from 0 to n. At the first step, you want to print n, then all the numbers from n-1 to 0 and from 0 to n-1, and print another n. See where it's going?
So, you have to do something like this:
print(n)
call f(n-1)
print(n)
I hope my explanation is clear enough.
This is more of hack -- using the std::stream rather than recursion...
void rec(int n) {
if (n==1) { cout << 1; return; }
cout << n;
rec(n-1);
cout << n;
}
int main() {
rec(3);
}
prints
32123
I'm working on a fairly easy tracing exercise however I'm not completely understanding why the solution is what it is...
void f( int n) {
if (n>0) {
f(n-1)
cout << n << " ";
}
}
int main () {
f(5);
return 0;
}
the answer is 1 2 3 4 5, however I'm wondering how this is so, since everytime the function f is called it never gets to the cout line...I understand that there is a stacking system where the last function implemented is looked at, however until the factorial example where it returned a value to multiply to the previous n, I'm not understanding how this is similar. Please don't use the factorial example again, I do understand it, but I'm not udnerstanding how the cout is implemented here.. thank you for your help.
Consider the simple case of calling f(1). We pass the if test and make a recursive call to f(0). This call will return doing nothing and continue executing the body of f(1). The next statement is the call to std::cout << 1 << " ";:
// Substitute the parameter with the passed in argument n = 1
void f(1) {
if (1 > 0) {
f(0);
std::cout << 1 << " ";
}
}
You should now be able to handle the case of f(2), and in general f(n). Whenever you are stuck thinking about recursive programs, consider the base cases and then generalize. Write the code out by substituting the function parameters with actual arguments.
It does get to the output line, after the recursive call to f returns.
The important part here is the stopping condition:
if (n>0)
This makes the recursive call only happen if n is larger than zero. And as the recursive call is with the argument n - 1 it will be lower and lower until it's zero and no more calls will be made.
Lets trace it for you, since you are to lazy to do it yourself in a debugger (or on paper):
The first call from main is made. n == 5 and clearly larger than zero, so a recursive call is made with 5 - 1
In the second call, n == 4, still larger than zero so a call is made again with 4 - 1
In the third call, n == 3, still larger than zero so a call is made again with 3 - 1
In the fourth call, n == 2, still larger than zero so a call is made again with 2 - 1
In the fifth call, n == 1, still larger than zero so a call is made again with 1 - 1
In the sixth call, n == 0, which is not larger than zero, so no more calls are made and the function returns.
Returns to n == 1, and so 1 is printed and then the function returns
Returns to n == 2, and so 2 is printed and then the function returns
Returns to n == 3, and so 3 is printed and then the function returns
Returns to n == 4, and so 4 is printed and then the function returns
Returns to n == 5, and so 5 is printed and then the function returns to the main function
That is, this is how it should have worked if it compiled. Now it won't even get this far since you will have compiler errors (with the code as shown in your question).