当前位置: 代码迷 >> C语言 >> [求助] 二叉树问题
  详细解决方案

[求助] 二叉树问题

热度:327   发布时间:2007-01-06 23:51:08.0
[求助] 二叉树问题

#include "stdio.h"
#include "alloc.h"

struct shu
{
int data;
struct shu *lchild, *rchild;
};
struct shu * grate()
{
struct shu *t;
char ch;
printf ("enter a char\n");
scanf ("%c", &ch);
if (ch==' ')
t=NULL;
else {
t=(struct shu *) malloc (sizeof (struct shu));
t->data=ch;
t->lchild=grate ();
t->rchild=grate ();
}
return t;
}

void print (struct shu *p)
{
if (p==NULL)
printf ("error\n");

else{
printf ("%c", p->data);
print (p->lchild);
print (p->rchild);
}

}

main ()
{
struct shu *t ;
t=grate ();
print (t);
getch ();
}

为什么不能创建二叉树。



搜索更多相关的解决方案: 二叉树  

----------------解决方案--------------------------------------------------------

[CODE]#include "stdio.h"
#include "stdlib.h"
struct shu
{
int data;
struct shu *lchild, *rchild;
};
struct shu * grate()
{
struct shu *t;
char ch;
printf ("enter a char\n");
ch=getchar();
fflush(stdin);//问题出在这里,scanf在读不进空格.

if (ch==' ')
t=NULL;
else {
t=(struct shu *) malloc (sizeof (struct shu));
t->data=ch;
t->lchild=grate ();
t->rchild=grate ();
}
return t;
}
void print (struct shu *p)
{
if (p==NULL);//为了让先序遍历好看点
else{
printf ("%c", p->data);
print (p->lchild);
print (p->rchild);
}
}
main ()
{
struct shu *t ;
t=grate ();
print (t);
return 0;
}[/CODE]


----------------解决方案--------------------------------------------------------
怎样输入才能完成创建和输出
----------------解决方案--------------------------------------------------------

按照二叉树的先序遍历输入,如
abc####就表示一棵以a为根,bc分别为 a的左右子树.(#表示空格)


----------------解决方案--------------------------------------------------------
终结符最好就是用#或其他特定的字符,不要用空格
----------------解决方案--------------------------------------------------------

还是不行, 没办法


----------------解决方案--------------------------------------------------------
原本是让你输入一个字符换一行的,因为你每次调用都printf了一行。
也就是说abc####得这样输入(#为空格,不过,如5楼版主所说,不提倡用空格,不明显)
a
b
#
#
#
#
如果你要一次都输入完毕,那就把fflush();这句去掉吧.
----------------解决方案--------------------------------------------------------
程序中通过调用grate()来建立树,
树中建立左孩子及又孩子时,也是通过调用grate()函数,
在建立左孩子树时,又要求为下一个左孩子建立(如果输入的是非空格字符)……
如此便构成了一个没法结束的递归调用。
----------------解决方案--------------------------------------------------------
以下是引用ChenMo在2007-1-7 19:38:45的发言:
程序中通过调用grate()来建立树,
树中建立左孩子及又孩子时,也是通过调用grate()函数,
在建立左孩子树时,又要求为下一个左孩子建立(如果输入的是非空格字符)……
如此便构成了一个没法结束的递归调用。

只有当ch不是空格时才调用,这便是递归的出口。


----------------解决方案--------------------------------------------------------
if (ch==' ')-> if (ch=='\n')
每输入一个字母按一次回车,然后按n(字母个数)次回车才输出。
谢谢!


----------------解决方案--------------------------------------------------------
  相关解决方案