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;i<n;i++) { scanf(“%s”,str); r=&(root[0]); for (j=0;str[j];j++) { if (r->next[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<Q;i++) { scanf(“%s”,str); solve(); printf(“/n”); } return 0; }

    原文作者:Trie树
    原文地址: https://blog.csdn.net/qiuzhenguang/article/details/5633770
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞