我如何不使用循环就可以编写此函数? (同时)我只能使用递归 [英] how can ı write this function without using loop ? (while,for) I can only use recursion
问题描述
void draw(int x[max], int a, int bh) {
int i;
if(a<=max){
if([root]!=-1)
{
if(
draw(x,2*a+1,depth
for(i=0;i<bi++)
{
printf("\t");
}
printf("%d\n",x[a]);
if(b>0)
{
draw(x,2*a+2,b-1);
}
}
}
}
如何编写没有循环的代码? (暂无) 我只能使用递归.
how can I write this code without loop? (without for,while) I can only use recursion.
推荐答案
我不希望您避免使用用于创建缩进的循环,但实际上可以将其替换为递归.
I don't think you're expected to avoid the loop used to create the indenting, but it can indeed be replace with recursion.
要找到打印N个标签的递归解决方案,我们问自己:如何通过打印不同数量的标签来定义N个标签的打印?
To find a recursive solution to printing N tabs, we asked ourselves: How can I define printing N tabs in terms of printing a different number of tabs?
那么,您可以先打印一个标签,然后再打印N-1个标签,以打印N个标签.
Well, you can print N tabs by printing one tab, then printing N-1 tabs.
void print_indent(unsigned i) {
if (!i)
return;
printf("\t");
print_indent(i-1);
}
print_indent(depth);
实际上,任何循环都可以用递归代替.
In fact, any loop can be replaced with recursion.
我们知道我们可以通过循环消除尾调用递归.通过相反的过程,我们知道
We know we can eliminate tail call recursion with a loop. By doing the process in reverse, we know that
while (cond()) {
body();
}
可以写为
void recursive_loop() {
if (!cond())
return;
body();
recursive_loop();
)
recursive_loop();
我们也知道
for (init(); cond(); post()) {
body();
}
只是另一种写作方式
init();
while (cond()) {
body();
post();
}
如此
for (int i=0; i<depth; ++i) {
printf("\t");
}
可以写为
void print_indent(int depth, int i) {
if (i >= depth) {
return;
printf("\t");
++i;
print_indent(depth, i);
}
int i = 0;
print_indent(depth, i);
这篇关于我如何不使用循环就可以编写此函数? (同时)我只能使用递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!