typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}*Tree, Tnode;
static void CreateTree(Tree *T);
题目:二叉排序树
就一个函数:创建函数.
条件是:CreateTree()函数只能有一个参数,那就是"根".不能有同数据域相同类型的参数
创建成功者给3000金币
下面是排序树程序,我的意思是想改变CreateTree()函数,现在输入创建的值不是在main()中输入的吗?我不想在main()中输入ch值,而是在CreateTree()函数中输入,也就是将CreateTree()该成CreateTree(Tree *T)的形式.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}*Tree, Tnode;
static void CreateTree(Tree *T, char ch);
static void VisitTree(Tree *T);
int main(void)
{
Tree T = NULL;
char ch;
printf("Enter create tree string: \n");
fflush(stdin);
while (1)
{
scanf("%c", &ch);
if (ch == '\n')
{
break;
}
CreateTree(&T, ch); /* 创建二叉排序树 */
}
VisitTree(&T); /* 打印二叉排序树 */
printf("\n");
return 0;
}
static void CreateTree(Tree *T, char ch)
{
if (*T == NULL)
{
if (((*T) = (Tree)malloc(sizeof(Tnode))) == NULL)
{
exit(1);
}
(*T) -> data = ch;
(*T) -> lchild = NULL;
(*T) -> rchild = NULL;
}
else
{
if ((*T) -> data > ch)
{
CreateTree(&(*T) -> lchild, ch);
}
else if ((*T) -> data < ch)
{
CreateTree(&(*T) -> rchild, ch);
}
}
}
static void VisitTree(Tree *T)
{
if (*T != NULL)
{
VisitTree(&(*T) -> lchild);
printf("%c", (*T) -> data);
VisitTree(&(*T) -> rchild);
}
free(*T);
}
这样可以吧:
# include <stdio.h>
# include <stdlib.h>
struct btnode
{
int data;
struct btnode *lchild,*rchild;
};
struct btnode *CreateTree(struct btnode *bt)
{
struct btnode *head,*p1,*p2,*q;
int i,j,k,a[100]={0};
for(i=0;i<100;i++)
{
scanf("%d",&a[i]);
if(a[i]==-1) break;
}
for(j=0;j<i;j++)
{
q=(struct btnode *)malloc(sizeof(struct btnode));
q->data=a[j]; q->lchild=q->rchild=NULL;
p1=bt;
if(p1==NULL) bt=p1=q;
else
{
while(p1)
{
p2=p1;
if(a[j]<p1->data)
{p1=p2->lchild;k=1;}
else
{p1=p2->rchild;k=0;}
}
if(k==1) p2->lchild=q;
else p2->rchild=q;
}
}
return(bt);
}
void bianli2(struct btnode *t) /* 递归中序遍历 */
{
if (t!=NULL)
{
bianli2(t->lchild);
printf("%d ",t->data);
bianli2(t->rchild);
}
return;
}
main()
{
struct btnode *bt=NULL;
bt= CreateTree(bt);
bianli2(bt);
getch();
}
我用的是int型.输入数字时要用回车.遇-1结束..按你的要求
CreateTree()函数 只有一个头指针bt
还有..你照书写的递归算法实在不怎么样..这道题根本就用不着递归!
强强,不过我就会递归的,兄弟,用递归能在写一个吗
,看着简单啊