[英]Visualizing recursion for binary tree
Write a recursive function that displays all the binary (base 2) numbers represented by a string of xs, 0s, and 1s. 编写一个递归函数,以显示由xs,0s和1s字符串表示的所有二进制(以2为底)数字。 The xs represent digits that can be either 0 or 1. For example, the string xx represents the numbers 00,01,10,11.
xs表示可以为0或1的数字。例如,字符串xx表示数字00、01、10、11。
The code works, but I just have a hard time visualizing the intermediate steps. 该代码有效,但是我很难想象中间步骤。 Could someone help me walkthrough?
有人可以帮助我演练吗?
void get_first_x(char *line,char *line2,char *line3);
void display(char *line);
int main(int argc, const char * argv[]) {
char line[256];
printf("Binary number: ");
scanf("%s",line);
display(line);
return 0;
}
void display(char *line){
char line2[80];
char line3[80];
if(strchr(line,'x') == NULL)
{
printf("%s\n",line);
return;
}
get_first_x(line,line2,line3);
display(line2);
display(line3);
}
void get_first_x(char* line,char* line2,char *line3) {
char* check;
check = strchr(line,'x');
*check = '0';
strcpy(line2,line);
*check = '1';
strcpy(line3,line);
}//replacement of x with 0 and 1. One argument produces 2 strings
Here's my take
这是我的
1st call display(xx)
2nd call display(0x)
3rd call display(00) { print statement/ return}
display(1x)
display(01) { print statement/return}
display(10) { print statement/return}
recursion exits
Input: xx
output: 00,01,10,11
I'm not understanding something...here
What you implemented is this (in pseudo code): 您实现的是(用伪代码):
display(line) {
if no_x_in(line) {
print(line) // instance output and recursion stop
}
display(replace_first_x_with_0(line)) // recursive call
display(replace_first_x_with_1(line)) // recursive call
}
If the string in line
contains no x
symbols anymore you can output the string and your recursive descent can stop. 如果该
line
中的字符串不再包含x
符号,则可以输出该字符串,并且递归下降可以停止。
If not, the problem instance is reduced from a line
with n times many x
symbols into two smaller instances, each with n - 1 many x
symbols, 如果不是,则将问题实例从具有n个
x
符号的line
简化为两个较小的实例,每个实例具有n-1个 x
符号,
x
replaced by a 0
symbol and x
替换为0
符号,然后 x
replaced by a 1
symbol. x
代替1
符号。 which result into a recursive call each. 这导致每个递归调用。 As there are only finite many
x
symbols in the finite input string, the recursive calls will stop at some point, and the resulting call tree is finite as well. 由于在有限的输入字符串中只有有限的
x
符号,因此递归调用将在某个点处停止,并且生成的调用树也将是有限的。
For your example the call tree is like this: 对于您的示例,调用树如下所示:
display('xx') -> issues calls to display('0x') and display('1x')
|
+-> display('0x') -> issues calls to display('00') and display('01')
| |
| +-> display('00') -> output, stop
| +-> display('01') -> output, stop
|
+-> display('1x') -> issues calls to display('10') and display('11')
|
+-> display('10') -> output, stop
+-> display('11') -> output, stop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.