hiho#1014-Trie树

#include<iostream>
#include<cstdio>
#define L 11
using namespace std;
//定义结构体Node,包含26个子节点位置以及以该节点为根节点的树拥有的完整单词的数目
typedef struct Node{
  int num;//
  struct Node *child[26];
  Node(){
    num = 0;
    int i;
    for(i=0;i<26;i++){
        child[i] = NULL;
    }
  }
}Node;

//字典树根节点和要插入的单词作为参数传入,<span style="font-family: Arial, Helvetica, sans-serif;">从根节点逐个检查字符串中的字符</span>
void InTree(Node *root, char word[]){
    for(int i=0;word[i];i++){
        int pos = word[i]-'a';
        if(root->child[pos] == NULL)
            root->child[pos] = new Node();
        root->child[pos]->num++;
        root = root->child[pos];
    }
}

//<span style="font-family: Arial, Helvetica, sans-serif;">字典树根节点和前缀字符串作为参数传入,从根节点逐个检查字符串中的字符</span>
int findTree(Node* root, char word[]){
    for(int i=0;word[i];i++){
        int pos = word[i]-'a';
        if(root->child[pos] == NULL)
            return 0;
        root = root->child[pos];
    }
    return root->num;
}
int main()
{
    int n,m;
    char dic[L];
    char w[L];
    Node *tnode = new Node();
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>dic;
        InTree(tnode, dic);
    }
    cin>>m;
    for(int i=0;i<m;i++){
        cin>>w;
        cout<<findTree(tnode, w)<<endl;
    }
    return 0;
}

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