Trie tree 字典树的实现

const int _Size = 26;

struct TrieTreeNode {
	int num;			// (标记该节点是否可以形成一个单词,如果count!=0, 则根节点到该节点可以形成一个单词)
	TrieTreeNode* next[_Size];
	/*
	TrieTreeNode() {
		num = 1;
		for (int i = 0; i < _Size; i++) {
			next[i] = NULL;
		}
	}
	*/
};

//创建Trie节点树
TrieTreeNode* createTrie() {
	TrieTreeNode* node = new TrieTreeNode;
	for (int i = 0; i < _Size; i++) {
		node->next[i] = NULL;
	}
	node->num = 1;
	return node;
}

//插入一个字符串
void Trie_Insert_str(TrieTreeNode* root, char *str) {
	TrieTreeNode* p = root;
	int len = strlen(str);
	
	for (int i = 0; i < len; i++) {
		int index = str[i] - 'a';
		if (p->next[index] == NULL) {
			TrieTreeNode* temp = createTrie();
			p->next[index] = temp;
			p = p->next[index];
		}
		else {
			p = p->next[index];
			p->num++;
		}
	}
}

//查找字符串
int Trie_Search_str(TrieTreeNode* root, char *str) {
	TrieTreeNode* p = root;
	int len = strlen(str);
	int _nums = 0;
	for (int i = 0; i < len; i++) {
		int index = str[i] - 'a';
		if (p->next[index] == NULL) {
			cout << "不存在字符串(前缀): ";
			_nums = 0;
			return 0;
		}
		else {
			p = p->next[index];
			_nums = p->num;
		}
	}
	return _nums;
}

/**************************************************************************************/
//从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串
TrieTreeNode* creatTrie_1() {
	TrieTreeNode* node = new TrieTreeNode;
	for (int i = 0; i < _Size; i++) {
		node->next[i] = NULL;
	}
	node->num = 0;
	return node;
}

void Trie_Insert_str_1(TrieTreeNode* root, char* str) {
	if (root == NULL || *str == '\n') {
		return;
	}

	TrieTreeNode* p = root;
	char* temp = str;

	while (*temp != '\0') {
		int index = *temp - 'a';
		if (p->next[index] == NULL) {
			TrieTreeNode* _tmp = creatTrie_1();
			p->next[index] = _tmp;
		}
		p = p->next[index];
		temp++;
	}
	p->num++;
}

void Trie_Search_str_1(TrieTreeNode* root, char* str) {
	if (root == NULL || *str == '\0') {
		cout << "Trie tree or str is empty" << endl;
		return;
	}

	char* temp = str;
	TrieTreeNode* p = root;

	while (*temp != '\0') {
		int index = *temp - 'a';
		if (p->next[index] != NULL) {
			p = p->next[index];
			temp++;
		}
		else
			break;
	}
	
	if (*temp == '\0') {
		if (p->num == 0)
			cout << "该字符串是Trie树中某个单词的前缀" << endl;
		else
			cout << "该字符串在Trie树中" << endl;
	}
	else
		cout << "该字符串不在Trie树中" << endl;
}

 

    原文作者:Trie树
    原文地址: https://blog.csdn.net/jihao0919/article/details/86603825
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞