所谓字典树,就是用树的结构,构造字符串 ,并且根据先序遍历可以,完成排序,区别于一般的BST 中序遍历 即可完成排序
,还有我这个有一些缺陷,一般其中有个数据n ,代表的是这个下面还有多少个字串是拥有公共前缀,所以你懂的,板子,
#include<stdio.h> #include<stdlib.h> #include<string.h> #define f(i,l,r) for(int i=l;i<=r;++i) typedef struct node{ int n; char * str; struct node* next[26]; }TrixTree; TrixTree * createNode(){ TrixTree * p = (TrixTree* ) malloc( sizeof(TrixTree)); memset(p,0,sizeof(TrixTree)); return p; } void addNode(TrixTree * pRoot,char * str){ if(pRoot==NULL||str==NULL)return ; f(i,0,strlen(str)-1){ if(pRoot->next[str[i]-97]==NULL) pRoot->next[str[i]-97]=createNode(); pRoot = pRoot->next[str[i]-97]; } pRoot->n++; pRoot->str = str; } TrixTree * build( char *str[],int n ){ if( str ==NULL ||n<1)return NULL; TrixTree * pRoot = createNode(); f(i,0,n-1) addNode(pRoot,str[i]); return pRoot; } void travelTree(TrixTree * pRoot){ if(pRoot==NULL)return ; if(pRoot->n) printf("%s\n",pRoot->str); f(i,0,25) travelTree(pRoot->next[i]); } void find(TrixTree * pRoot,char * str) { if(pRoot==NULL||str==NULL)return ; f(i,0,strlen(str)-1){ if(pRoot->next[str[i]-97]==NULL)return ; pRoot=pRoot->next[str[i]-97]; } printf("%d \n",pRoot->n); } int main(){ char * str[]={"hello","world","hello","my","trixtree"}; TrixTree * pRoot = build(str,5); travelTree(pRoot); return 0; }
未来的我一定会感谢现在正在成长的我!