【树】Trie树

#include<iostream>
#include<string>
using namespace std;
//Trie树结点
struct TrieNode{
	bool is_string;//标记该结点处是否构成单词 
	TrieNode* next[26];
	TrieNode() :is_string(false){
		for (int i = 0; i < 26; i++)
			next[i] = NULL;
	}
};
//Trie树
class TrieTree{
public:
	TrieTree();
	~TrieTree();
	void insert(string str); //将单词str插入到字典树中 
	bool search(string str);//查找某个单词是否已经存在 
	void del(TrieNode* tn);//释放整个字典树占的堆区空间
private:
	TrieNode* root;
};

TrieTree::TrieTree() :root(new TrieNode){}
TrieTree::~TrieTree(){ del(root); }
void TrieTree::insert(string str){  //将单词str插入到字典树中 
	if (root == NULL || str.size() == 0)
		return;
	TrieNode* p = root;
	for (int i = 0; i < str.size(); i++){
		if (p->next[str[i] - 'a'] == NULL){
			TrieNode* temp = new TrieNode;
			p->next[str[i] - 'a'] = temp;
			p = p->next[str[i] - 'a'];
		}
		else{
			p = p->next[str[i] - 'a'];
		}
	}
	p->is_string = true; //单词结束时标记此处构成一个单词 
}
bool TrieTree::search(string str){//查找某个单词是否已经存在 
	TrieNode* p = root;
	for (int i = 0; p != NULL&&i < str.size(); i++){
		p = p->next[str[i] - 'a'];
	}
	return (p != NULL&&p->is_string == true);//单词结束处标记为true时,单词才存在
}
void TrieTree::del(TrieNode* tn){//释放整个字典树占的堆区空间
	for (int i = 0; i < 26; i++){
		if (tn->next[i] != NULL)
			del(tn->next[i]);
	}
	delete tn;
}

int main(){
	int i, num;
	string str;
	TrieTree trie_tree;
	cin >> num;
	for (i = 0; i<num; i++){
		cin.clear();
		cin.sync();
		cin >> str;
		trie_tree.insert(str);
	}

	cin >> num;
	for (i = 0; i<num; i++){
		cin >> str;
		if (trie_tree.search(str)){
			cout << str << " is in trie tree" << endl;
		}
		else{
			cout << str << " is not in trie tree" << endl;
		}
	}
	return 0;
}

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