您的位置:首页 > 其它

Tried树 (字典查找树)的创建

2016-07-14 22:20 218 查看
数的创建

//字典查找树的实现
#include<iostream>
using namespace std;
struct Tried
{
int count;//用来标记该节点是个可以形成一个单词,如果count!=0,则从根节点到该节点的路径可以形成一个单词
Tried* next[26];
};
Tried* createNode()
{
Tried* node = new Tried();
node->count = 0;
memset(node->next,0,sizeof(node->next));
return node;
}
//向树中插入单词
void insert(Tried* root,char* word)
{
if (root == NULL || *word == '\0')return;
int len = strlen(word);
Tried* node = root;
char* p = word;
while(*p!='\0')
{
if (node->next[*p - 'a'] == NULL)
{
node->next[*p - 'a'] = createNode();
}
node = node->next[*p-'a'];
p++;
}
node->count++;
}
//查找单词
bool search(Tried * root,char* word)
{
if (root==NULL||*word=='\0')return false;
Tried* node = root;
char* p = word;
while (*p!='\0')
{
if (node->next[*p - 'a'] == NULL)
break;
node = node->next[*p-'a'];
p++;
}
if (*p != '/0')return false;
else
{
if (node->count != 0)return true;
else return false;
}
}
//返回单词查询次数
int count(Tried* root,char* word)
{
if (root == NULL || *word == '\0')return 0;
char* p = word;
Tried* node = root;
while (*p!='\0')
{
node = node->next[*p-'a'];
p++;
}
return node->count;
}

主函数
int main()
{
Tried* root = createNode();
char word[][10] = {"test", "study", "open", "show", "shit", "work", "work", "test", "tea", "word", "area", "word", "test", "test", "test"};
//用word创建树
for (int i = 0; i < 15;i++)
{
insert(root, word[i]);
}
for (int i = 0; i < 15; i++){
cout << "the word " << word[i]<< " appears" << count(root, word[i]) << " times in the trie-tree" << endl;
}
//查找树中没有的单词
char s[10] = "testit";
if (!search(root, s))
cout << " the word testit isn't appear in the tree" << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: