字典树
字典树(TrieTree):功能:查找,排序,计数
看名字理解,就像查字典一样的查找,即首字母为a从一处开始查找,首字母为b的从某一处开始查找。
这样我们就建成了26叉树,每一个叉代表一个字母,根不表示字母。
那么比如说字符串数组:acd abc 我们再这个数组中找ab,那么也会找到,所以我们就需要再节点的结构体中加一个参数,表示结束,这个参数除了表示结束也可以计数,看字符串数组中有几个这样的字符串 。
对于排序的功能:我们在每一个结尾位置存储该字符串,这样方便遍历,在节点中添加一个参数记录。既然是树就可以按照前序输出,即先输出根再输出26个孩子,这样输出的就是按每个字母顺序的了。
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node { int Count; char* str; struct node* next[26]; }Node; Node* CreateNode() { Node* tmp = (Node*)malloc(sizeof(Node)); tmp->Count = 0; memset(tmp,0,sizeof(Node)); return tmp; } Node* CreateTree(char **str,int len) { Node* pRoot = CreateNode(); int id = 0; Node* flag = pRoot; for(int i = 0; i < len;i++) { id = 0; flag = pRoot; while(id < strlen(str[i])) { if(flag->next[str[i][id]-97] == NULL) { flag->next[str[i][id]-97] = CreateNode(); } flag = flag->next[str[i][id]-97] ; id++; } flag->Count ++; flag->str = str[i]; } return pRoot; } void Search(Node* pRoot,char* match) { int id = 0; Node* tmp = pRoot; while(match[id]!='\0') { tmp = tmp->next[match[id]-97]; if(tmp == NULL) { printf("failed\n"); return; } id++; } if(tmp->Count == 0) { printf("failed\n"); return; } else printf("%s \n",tmp->str); } void Traversal(Node *pTree) { if(pTree == NULL)return; if(pTree->Count != 0) { printf("%s\n",pTree->str); } int i; for(i = 0;i<26;i++) { Traversal(pTree->next[i]); } } int main() { char* str1 = "abc"; char* str2 = "aac"; char* str3 = "bac"; char* str4 = "cca"; char* str[] = {str1,str2,str3,str4}; Node* pRoot = CreateTree(str,4); Traversal(pRoot); Search(pRoot,"ghjk"); }