思路:创建一个键对
typedef struct Dict
{
char en[20];//key
char cn[20];//value
struct Dict *_pLeft;
struct Dict *_pRight;
}Dict;
Dict* BuyDictNode(char en[],char cn[])
{
Dict* pNewNode = (Dict*)malloc(sizeof(Dict));
if (pNewNode == NULL)
{
perror("malloc::BuyBSTreeNode");
return NULL;
}
//pNewNode->_data = data;
strcpy(pNewNode->en, en);
strcpy(pNewNode->cn, cn);
pNewNode->_pLeft = NULL;
pNewNode->_pRight = NULL;
return pNewNode;
}
bool InSertDict(Dict** pRoot, char en[], char cn[])//插入
{
int ret = 0;
assert(pRoot);
if (*pRoot == NULL)
{
*pRoot = BuyDictNode(en,cn);
return true;
}
else
{
ret = strcmp(en, (*pRoot)->en);
if (0 == ret)
return false;
else if (ret < 0)
return InSertDict(&(*pRoot)->_pLeft, en,cn);
else
return InSertDict(&(*pRoot)->_pRight, en,cn);
}
}
Dict* FindDict(Dict* pRoot, char en[])
{
int ret = 0;
if (NULL == pRoot)
return NULL;
ret = strcmp(en, (pRoot)->en);
if (ret == 0)
return pRoot;
else if (0 > ret)
return FindDict(pRoot->_pLeft, en);
else
return FindDict(pRoot->_pRight, en);
}
void InOrderDict(Dict* pRoot)//中序遍历
{
if (pRoot)
{
InOrderDict(pRoot->_pLeft);
printf("%s %s\n", pRoot->en,pRoot->cn);
InOrderDict(pRoot->_pRight);
}
}
void test()
{
Dict *pRoot = NULL;
InSertDict(&pRoot, "apple","苹果");
InSertDict(&pRoot, "pear","梨");
InSertDict(&pRoot, "banana","香蕉");
InSertDict(&pRoot,"abaka","阿巴卡");
InOrderDict(pRoot);
char arr[20];
while (1)
{
scanf("%s", &arr);
Dict *word = FindDict(pRoot, arr);
if (word == NULL)
printf("拼写错误\n");
else
printf("%s 拼写正确\n", word->cn);
}
}
运行结果如图: