Trie树

一、Trie树,又叫字典树,就是将字典存入到树中,方便进行单词匹配。

其实实现起来很简单,模版如下:

//动态分配内存

struct Trie
{
	int count;
	Trie *next[26];
	Trie()
	{
		count = 0;
		memset(next, 0, sizeof(next));
	}
};

void buildTrie(Trie *root, char *s, int len)
{
	Trie *p = root;
	int i;
	for(i = 0; i < len; ++ i)
	{
		int index = s[i] - 'a';
		if(root->next[i] == NULL) root->next[i] = new Trie();
		p = p ->next[i];
	}
	p->count ++;
}

void deleteTrie(Trie *root)
{
	int i;
	for(i = 0; i < 26; ++ i)
	{
		if(root->next[i])
			deleteTrie(root->next[i]);
	}
	delete(root);
}

//静态数组形式实现
struct Trie
{
	int count;
	Trie *next[26];
}trie[nMax];
int pos;

void buildTrie(char *s, int len)
{
	int i;
	Trie *p = &trie[0];
	for(i = 0; i < len; ++ i)
	{
		int index = s[i] - 'a';
		if(p->next[i] == NULL) p->next[i] = trie[pos ++];
		p = p->next[i];
	}
	p->count ++;
}


你可能感兴趣的:(Trie树)