二叉搜索树 ---- 模拟实现一个简单字典

思路:创建一个键对

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);
    }

}

运行结果如图:
这里写图片描述

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值