Trie树

Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。

Trie的简单实现(插入、查询)

  

#include <stdio.h>
#include <string>
using namespace std;

const int branchNum = 26;

struct Trie_node
{
	bool isStr;
	Trie_node *next[branchNum];
	Trie_node()
	{
		isStr = false;
		memset(next, NULL, sizeof(next));
	}
};

class Trie
{
public:
	Trie();
	~Trie();
	void insert(const char* word);
	bool search(char* word);
	void deleteTrie(Trie_node* root);

	Trie_node* root;
};

Trie::Trie()
{
	root = new Trie_node();
}
Trie::~Trie()
{
	deleteTrie(root);
}
void Trie::insert(const char* word)
{
	Trie_node *location = root;

	while (*word)
	{
		if (location->next[*word - 'a'] == NULL)
		{
			location->next[*word - 'a'] = new Trie_node();
		}
		
		location = location->next[*word-'a'];
		word ++;
	}

	location->isStr = true;
}

void Trie::deleteTrie( Trie_node* root )
{
	if (root == NULL)
	{
		return;
	}

	for (int i = 0; i < branchNum; i ++)
	{
		deleteTrie(root->next[i]);
	}
	
	delete root;
}

bool Trie::search( char* word )
{
	Trie_node *locaton = root;

	while (*word && locaton)
	{
		locaton = locaton->next[*word - 'a'];
		word ++;
	}
	
	return(locaton != NULL && locaton->isStr);
}


int main()
{
	Trie trie;
	trie.insert("helloworld!");
	trie.insert("he!");
	trie.insert("helloworlda!");

	if (trie.search("helloworld!"))
	{
		printf("true\n");
	}
	return 0;
}

 

posted @ 2017-10-29 14:31  Fate0729  阅读(180)  评论(0编辑  收藏  举报