#include<stdio.h>
#include<iostream>
#include<assert.h>
using namespace std;
const int MaxKeySize = 25;
const int LinkSize = 27;
typedef struct
{
char ch[MaxKeySize + 1];
int len;
}KeyType;
typedef struct {} Record;
typedef enum {ELEMENT = 0, BRANCH = 1} NodeType;
struct TrieNode;
typedef struct
{
KeyType key;
Record* recptr;
}ElemType;
typedef struct
{
struct TrieNode* link[LinkSize];
int num;
}BrachType;
typedef struct TrieNode
{
NodeType utype;
union
{
ElemType elem;
BrachType brach;
};
};
typedef struct
{
TrieNode* root;
}TrieTree;
TrieNode* BuyNode()
{
TrieNode* s = (TrieNode*)calloc(1, sizeof(TrieNode));
if (nullptr == s) exit(EXIT_FAILURE);
return s;
}
void FreeNode(TrieNode* ptr)
{
free(ptr);
}
void InitTrieTree(TrieTree* ptree)
{
ptree->root = nullptr;
}
int KeyPos(const KeyType kx, int i)
{
int pos = 0;
if (i < kx.len)
{
pos = tolower(kx.ch[i]) - 'a' + 1;//תΪСд
}
return pos;
}
TrieNode* SearchValue(TrieTree* ptree, const KeyType& kx)
{
if (ptree == nullptr || kx.len == 0) return nullptr;
TrieNode* ptr = ptree->root;
int i = 0;
while (ptr != nullptr && ptr->utype == BRANCH && i <= kx.len)
{
int index = KeyPos(kx, i);
ptr = ptr->brach.link[index];
++i;
}
if (ptr != nullptr && ptr->utype == ELEMENT && strcmp(ptr->elem.key.ch, kx.ch) != 0)
{
ptr = nullptr;
}
return ptr;
}
TrieNode* BuyLeaf(const ElemType& item)
{
TrieNode* s = BuyNode();
s->utype = ELEMENT;
s->elem = item;
return s;
}
TrieNode* BuyBranch(TrieNode* ptr,int k)
{
TrieNode* s = BuyNode();
s->utype = BRANCH;
int pos = KeyPos(ptr->elem.key, k);
s->brach.link[pos] = ptr;
return s;
}
void Insert(TrieNode*& ptr, const ElemType& item, int k)
{
if (ptr == nullptr)
{
ptr = BuyLeaf(item);
}
else if (ptr->utype == ELEMENT)
{
ptr = BuyBranch(ptr,k);
int pos = KeyPos(item.key, k);
Insert(ptr->brach.link[pos], item, k + 1);
}
else if (ptr->utype == BRANCH)
{
int pos = KeyPos(item.key, k);
Insert(ptr->brach.link[pos], item, k + 1);
}
}
void Insert_Item(TrieTree* ptree, const ElemType item)
{
assert(ptree != nullptr);
int k = 0;
Insert(ptree->root, item, k);
return;
}
int main()
{
KeyType key[] = { {"CAI",3},{"CAO",3},{"CHA",3},{"CHANG",5},{"CHAO",4},{"LIU",3},{"LI",2 } };
int n = sizeof(key) / sizeof(key[0]);
TrieTree tree;
InitTrieTree(&tree);
KeyType kx;
TrieNode* p = SearchValue(&tree, kx);
for (int i = 0; i < n; ++i)
{
ElemType item = { key[i],nullptr };
Insert_Item(&tree, item);
}
}
字典树(T树)
于 2023-08-22 15:27:20 首次发布