trie树的DFS遍历

//trie树的dfs遍历 #include "stdio.h" #include "stdlib.h" #include "string.h" #define MAXN 10009 typedef struct trie { char num; int deep; struct trie *next[26]; }trie; trie root[20*MAXN]; char str[25],res[25]; int k; int dfs(trie *r,int k,int f) { int i,flag=0,max=0; for (i=0;i<26;i++) { if (r->next[i] != NULL) { flag=1; max=i; } } if (flag==0 && f==1) { res[k]='/0'; printf("%s",res); return 0; } if (r->deep==0) { res[k]=0; printf("%s ",res); } for (i=0;i<26;i++) { if (r->next[i]!=NULL) { res[k]=r->next[i]->num; if (max==i && f==1) dfs(r->next[i],k+1,1); else dfs(r->next[i],k+1,0); } } return 0; } int solve() { int j=0; trie *r =&(root[0]); while (str[j] && r->next[str[j]-'a'] != NULL ) { r = r->next[str[j]-'a']; j++; } if (str[j]) { printf("%s",str); //no such word } else { strcpy(res,str); k=strlen(res); dfs(r,k,1); } return 0; } int main() { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); int n,i,j,Q,cnt=0; trie *r; scanf("%d",&n); memset(root,0,sizeof(root)); for (i=0;inext[str[j]-'a']==NULL) { r->next[str[j]-'a']=&(root[cnt++]); r->next[str[j]-'a']->num = str[j]; r->next[str[j]-'a']->deep=r->deep+1; r=r->next[str[j]-'a']; } else { r=r->next[str[j]-'a']; } } r->deep = 0; } scanf("%d",&Q); for (i=0;i

你可能感兴趣的:(trie树的DFS遍历)