搜索二叉树基本概念请看上篇博客
这两个问题都是典型的K(key)V(value)问题,我们用KV算法解决。
结构声明下
typedef char* KeyType; typedef struct BSTreeNode { struct BSTreeNode *_left; struct BSTreeNode *_right; KeyType _key; }BSTreeNode;
插入,查找函数代码如下:
int BSTreeNodeInsertR(BSTreeNode **tree,KeyType key) //搜索树的插入 { int tmp = 0; if(*tree == NULL) { *tree = BuyTreeNode(key); return 0; } tmp = strcmp((*tree)->_key,key); if (tmp>0) return BSTreeNodeInsertR(&(*tree)->_left,key); else if (tmp<0) return BSTreeNodeInsertR(&(*tree)->_right,key); else return -1; } BSTreeNode *BSTreeNodeFindR(BSTreeNode *tree,KeyType const key) //查找 { int tmp = 0; if (!tree) return NULL; tmp = strcmp(tree->_key,key); if (tmp > 0) return BSTreeNodeFindR(tree->_left,key); else if (tmp < 0) return BSTreeNodeFindR(tree->_right,key); else return tree; }
测试代码:
void TestApplication() { BSTreeNode *tree = NULL; BSTreeNodeInsertR(&tree,"hello"); BSTreeNodeInsertR(&tree,"world"); BSTreeNodeInsertR(&tree,"int"); BSTreeNodeInsertR(&tree,"char"); BSTreeNodeInsertR(&tree,"float"); BSTreeNodeInsertR(&tree,"double"); printf("%s \n", BSTreeNodeFindR(tree,"char")->_key); printf("%s \n", BSTreeNodeFindR(tree,"double")->_key); printf("%s \n", BSTreeNodeFindR(tree,"int")->_key); printf("%s \n", BSTreeNodeFindR(tree,"float")->_key); printf("%s \n", BSTreeNodeFindR(tree,"hello")->_key); printf("%s \n", BSTreeNodeFindR(tree,"world")->_key); printf("%p \n", BSTreeNodeFindR(tree,"chars")); printf("%p \n", BSTreeNodeFindR(tree,"str")); }
测试结果:
结构构建
typedef char* KeyType; typedef int ValueType; typedef struct BSTreeNode { struct BSTreeNode *_left; struct BSTreeNode *_right; KeyType _key; ValueType _count; }BSTreeNode;
查找函数与上面相同,插入函数有所改变。
int BSTreeNodeInsertR(BSTreeNode **tree,KeyType key, ValueType value) //搜索树的插入 { int tmp = 0; if(*tree == NULL) { *tree = BuyTreeNode(key,value); return 0; } tmp = strcmp((*tree)->_key,key); if (tmp>0) return BSTreeNodeInsertR(&(*tree)->_left,key,value); else if (tmp<0) return BSTreeNodeInsertR(&(*tree)->_right,key,value); else return -1; }
测试代码:
void test() { BSTreeNode *tree = NULL; BSTreeNodeInsertR(&tree,"hello","你好"); BSTreeNodeInsertR(&tree,"world","世界"); BSTreeNodeInsertR(&tree,"char","字符"); BSTreeNodeInsertR(&tree,"int","×××"); BSTreeNodeInsertR(&tree,"float","浮点型"); printf("%s \n", BSTreeNodeFindR(tree,"char")->_value); printf("%s \n", BSTreeNodeFindR(tree,"int")->_value); printf("%s \n", BSTreeNodeFindR(tree,"float")->_value); printf("%s \n", BSTreeNodeFindR(tree,"hello")->_value); printf("%s \n", BSTreeNodeFindR(tree,"world")->_value); printf("%p \n", BSTreeNodeFindR(tree,"double")); }
测试结果
构建测试案例尽量构建全面,防止特殊情况被忽略。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。