Given the following recursive function, what would be printed by mysterious(4)?
void mysterious(int x) {
if (x ==开发者_如何学C 0) return;
printf(“%d ”, x);
mysterious(x-1);
mysterious(x-1);
}
Here is my call stack:
mysterious(4) => print 4
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(0) => print 0
Is this correct?
Because every function call makes 2 function calls in turn, you can visualize your recursion as a "tree" so to speak, and you are doing a preorder traversal on the tree.
It would look something like this:
4
|
3----------+----------3
| |
2----+----2 2----+----2
| | | |
1--+--1 1--+--1 1--+--1 1--+--1
The order of execution that you have is:
- print the number
- call the function with x-1
- call the function with x-1 again
This would correspond to our "tree visualization" by doing:
- print the root
- traverse the left node
- traverse the right node
The output would be:
4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Why don't you just type it in to an editor in your language of choice, compile it and run? I chose Java but that's just because I'm between CygWin installs on my box at the moment - I'd much rather be using C :-)
public class testprog {
public static void mysterious(int x) {
if (x == 0) return;
System.out.print(x + " ");
mysterious(x-1);
mysterious(x-1);
}
public static void main(String args[]) {
mysterious(4);
}
}
This outputs the numbers:
4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Basically, what's happening is that, at each level, you print out the number then call the next level twice with the next lowest number (unless it's reached zero).
Aside: technically, you do call the next layer with zero but, since it returns straight away, it has no affect on the output.
The following diagram will hopefully illustrate this better, with different symbols representing different layers:
(4) (-------------------------------) (-------------------------------)
{3} {-----------} {-----------} {3} {-----------} {-----------}
[2] [1] [1] [2] [1] [1] [2] [1] [1] [2] [1] [1]
No, it will be
mysterious(4) => print 4
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(1) => print 1
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(1) => print 1
mysterious(3) => print 3
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(1) => print 1
mysterious(2) => print 2
mysterious(1) => print 1
mysterious(1) => print 1
because 0 will cause the function to return earlier and because of that double-call.
No. It won't print 0
cause when x==0
it will return
Also, since you have
mysterious(x-1);
mysterious(x-1);
it will print (Fixed)
4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
mysterious(x-1);
doesnt change the value of x
. it just calls mysterious()
again, this time with the value x-1
精彩评论