1 (1)无冗余的接受键盘输入的n个字符串,并将其无冗余的放入对应的字符数组中,再按照每行一串的格式输出这些字符串。
(2)以单个字符串为数据域,按字典顺序将n个字符串生成为一棵二叉搜索树,并且规定左子树(数据域)小于右子树(数据域)。
(2)以单个字符串为数据域,按字典顺序将n个字符串生成为一棵二叉搜索树,并且规定左子树(数据域)小于右子树(数据域)。
(3)先序遍历该二叉树,并输出结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
char* data;
struct node *lchild,*rchild;
}BNode,*BTree;
void insert(BTree* t,char* data)
{
if(!(*t))
{
(*t)=(BTree)malloc(sizeof(BNode));
(*t)->data=data;
(*t)->lchild=NULL;
(*t)->rchild=NULL;
}
else
{
if(strcmp(data,((*t)->data))<0) insert(&(*t)->lchild,data);
else insert(&(*t)->rchild,data);
}
}
void PreOrder(BTree t)
{
if(t)
{
printf("%s\n",t->data);
PreOrder(t->lchild);
PreOrder(t->rchild);
}
}
int main()
{
int i;
int n;
scanf("%d",&n);
char** a=(char**)malloc(n*sizeof(char*));
if(a==NULL)
{
puts("malloc failed");
return 0;
}
for(i=0;i<n;i++)
{
int count=0;
char c;
a[i]=(char*)malloc(sizeof(char));
a[i][count++]=getchar();
while((c=getchar())!='\n')
{
a[i]=(char*)realloc(a[i],count*(sizeof(char)));
a[i][count++]=c;
}
a[i][count]='\0';
}
BTree t = NULL;
for(i=0;i<n;i++)
insert(&t,a[i]);
PreOrder(t);
system("pause");
return 0;
}