Trie树(字典树)

hihocoder的题就有这个,这里主要写了创建与查找,查找用了两种方式,迭代与递归

#include<iostream>
#include<string>
using namespace std;

typedef struct trieTree
{
	char word = 0;
	int counts = 0;
	struct trieTree* children[26] = {0};	//26个小写字母
}Trie;
Trie *root = new Trie;
void insertTree(string str,Trie *&root,int index = 0)
{
	if(index == str.length())
	{
		return;
	}
	int k = str[index] - 'a';	//字母映射成数字
	if(!root->children[k])
	{
		root->children[k] = new Trie;
	}
	root->children[k]->word = str[index];
	root->children[k]->counts++;
	insertTree(str, root->children[k], index + 1);
}

int search(string str, Trie* root)
{
	int i = 0;
	while(root && i < str.length())
	{
		int k = str[i] - 'a';
		root = root->children[k];
		i++;
	}
	if(i == str.length() && root)
	{
		return root->counts;
	}
	else
	{
		return 0;
	}
}

void search(string str, Trie* root, int &count, int index = 0)
{
	if (index < str.length())
	{
		int k = str[index] - 'a';
		if (!root->children[k])
		{
			count = 0;
		}
		else
		{
			count = root->children[k]->counts;
			search(str, root->children[k], count, index + 1);
		}
	}
}

int main()
{
	int n = 0, m = 0;
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		string str;
		cin >> str;
		insertTree(str, root);
	}
	cin >> m;
	for(int i = 0; i < m; i++)
	{
		string str;
		cin >> str;
		int count = 0;
		search(str, root,count);
		cout << count << endl;
	}
}


猜你喜欢

转载自blog.csdn.net/m0_37907835/article/details/78997612