🏷️TRIE
- The Trie data structure is a tree-like data structure used for storing a dynamic set of strings.
- 메모리 사용량은 비록 많아도 탐색 속도가 정말 빠르다.
- Using a Trie data structure we can insert, search and delete keys in a time complexity of O(k) where k is the length of the key.
- 어느정도 규칙이 있는 linux path(
/etc
, /boot
)같은 문자열에 더 빠른 탐색이 가능하도록 하는 방안 모색 중
📌Node
struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
int wordCount = 0;
};
📌Insertion
void insert_key(TrieNode* root, string& key)
{
TrieNode* currentNode = root;
for (auto c : key) {
if (currentNode->childNode[c - 'a'] == NULL) {
TrieNode* newNode = new TrieNode();
currentNode->childNode[c - 'a'] = newNode;
}
currentNode = currentNode->childNode[c - 'a'];
}
currentNode->wordCount++;
}
📌Searching
bool isPrefixExist(TrieNode* root, string& key)
{
TrieNode* currentNode = root;
for (auto c : key) {
if (currentNode->childNode[c - 'a'] == NULL) {
return false;
}
currentNode = currentNode->childNode[c - 'a'];
}
return true;
}
📌Deletion
bool delete_key(TrieNode* root, string& word)
{
TrieNode* currentNode = root;
TrieNode* lastBranchNode = NULL;
char lastBrachChar = 'a';
for (auto c : word) {
if (currentNode->childNode[c - 'a'] == NULL) {
return false;
}
else {
int count = 0;
for (int i = 0; i < 26; i++) {
if (currentNode->childNode[i] != NULL)
count++;
}
if (count > 1) {
lastBranchNode = currentNode;
lastBrachChar = c;
}
currentNode = currentNode->childNode[c - 'a'];
}
}
int count = 0;
for (int i = 0; i < 26; i++) {
if (currentNode->childNode[i] != NULL)
count++;
}
if (count > 0) {
currentNode->wordCount--;
return true;
}
if (lastBranchNode != NULL) {
lastBranchNode->childNode[lastBrachChar] = NULL;
return true;
}
else {
root->childNode[word[0]] = NULL;
return true;
}
}
📌References