#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
struct node
{
char *word;
char *meaning;
struct node *left;
struct node *right;
struct node *parent;
}*root=NULL,*trav,*tmp;
void add()
{
int res;
// create node
tmp=(struct node *) malloc(sizeof(struct node));
tmp->word=(char *)malloc(sizeof(char));
tmp->meaning=(char *)malloc(sizeof(char));
printf("\nEnter Word\n");
scanf("%[^\n]%*c",tmp->word);
printf("Enter Meaning\n");
scanf("%[^\n]%*c",tmp->meaning);
tmp->left=NULL;
tmp->right=NULL;
trav=root;
while(1)
{
if(trav==NULL)
{
root=tmp;
root->parent=NULL;
root->left=NULL;
root->right=NULL;
break;
}
else
{
res=strcmp(tmp->word,trav->word);
// if res==0 then words are same
// if res==1 then left word is alphabetically smaller
// if res==2 then left word is alphabetically bigger
if(res<0)
{
if(trav->left==NULL)
{
trav->left=tmp;
tmp->parent=trav;
break;
}
//goto left child
trav=trav->left;
}
else if(res>0)
{
if(trav->right==NULL)
{
trav->right=tmp;
tmp->parent=trav;
break;
}
//goto left child
trav=trav->right;
}
if(res==0)
{
printf("Word already exist\n");
break;
}
}
}
}
int main()
{
int flag=0;
while(1)
{
printf("\n1.add word\n2.delete word\n3.search word\n4.inorder traverse\n5.preorder traverse\n6.postorder traverse\n7.exit\n");
switch(getche())
{
case '1':
{
add();
break;
}
case '2':
{
delete_word();
break;
}
case '3':
{
search();
break;
}
case '4':
{
traverse_inorder(root);
break;
}
case '5':
{
traverse_preorder(root);
break;
}
case '6':
{
traverse_postorder(root);
break;
}
case '7':
flag=1;
}
if(flag==1)
break;
}
return 0;
}
/*
我正在创建一个基于树的字典,当我第三次执行 add 函数时,出现运行时错误,请帮助我*/ /* 错误出现在 malloc 函数上,当它第三次遇到时程序关闭*/