【发布时间】:2022-01-15 23:00:41
【问题描述】:
我需要创建一个 Trie 数据结构来存储 first name、last name 和 age。稍后我需要使用姓或名字和姓氏来实现对记录的搜索。
我知道如何创建 Trie、插入、删除和搜索。但是,我不知道如何适当地存储多个值(名字、姓氏和年龄)。
有人可以指点我正确的方向吗?
#include <string>
#include <iostream>
using namespace std;
const int ALPHA_SIZE = 26;
struct Trie
{
struct Trie* child[ALPHA_SIZE];
bool endofstring; //It is true if node represents end of word.
};
// Create new node
struct Trie* createNode(void)
{
struct Trie* tNode = new Trie;
tNode->endofstring = false;
for (int i = 0; i < ALPHA_SIZE; i++)
tNode->child[i] = NULL;
return tNode;
}
void insert(struct Trie* root, string key)
{
struct Trie* curr = root;
for (int i = 0; i < key.length(); i++) {
int index = key[i] - 'a';
if (!curr->child[index])
curr->child[index] = createNode();
curr = curr->child[index];
}
curr->endofstring = true; //last node as leaf
}
bool search(struct Trie* root, string key)
{
struct Trie* curr = root;
for (int i = 0; i < key.length(); i++) {
int index = key[i] - 'a';
if (!curr->child[index])
return false;
curr = curr->child[index];
}
return (curr != NULL && curr->endofstring);
}
bool isEmpty(Trie* root) //check if root has children
{
for (int i = 0; i < ALPHA_SIZE; i++)
if (root->child[i])
return false;
return true;
}
Trie* deletion(Trie* root, string key, int depth = 0)
{
//If tree is empty return null.
if (!root)
return NULL;
if (depth == key.size()) //If last character of key is being processed,
{
if (root->endofstring)
root->endofstring = false; //then that node will be no more end of string after deleting it.
if (isEmpty(root)) { //If given key is not prefix of any other string,
delete (root);
root = NULL;
}
return root;
}
//If key not last character,
int index = key[depth] - 'a';
root->child[index] =
deletion(root->child[index], key, depth + 1); //Then recur for the child which will be obtained by using ASCII value.
if (isEmpty(root) && root->endofstring == false) //If root does not have any child leftand it is not end of another word
{
delete (root);
root = NULL;
}
return root;
}
int main()
{
struct Trie* root = createNode();
insert(root, "joe");
insert(root, "hanna");
insert(root, "john");
insert(root, "jane");
search(root, "joe") ? cout << "Key is Found\n" :
cout << "Key is not Found\n";
search(root, "he") ? cout << "Key is Found\n" :
cout << "Key is not Found\n";
deletion(root, "john") ? cout << "Key is deleted\n" :
cout << "Key is not Deleted\n";
return 0;
}
【问题讨论】:
-
无关:您无需在任何地方输入
struct Trie*。一旦你定义了Trie类,它也是typedefined,所以你可以简单地写:Trie* -
谢谢。我在网上找到了例子。我会记住这一点的。
标签: c++ data-structures trie