C++实现Trie树数据结构构建与应用

2025年12月12日/ 浏览 21

以下是C++实现Trie树的完整示例代码,包括Trie树的构建、查找和优化功能:

cpp

include

include

include

class TrieNode {
public:
char* path;
vector<TrieNode> children;
bool isEnd;
private:
char
path;
vector<TrieNode*> children;
bool isEnd;
};

class TrieTree {
public:
TrieTree() : root(0) {}
TrieTree() : root(0) {}
~TrieTree() {}

    TrieTree() {
        root = new TrieNode();
    }

    // 建立Trie树
    void build(TrieTree& tree, const string& s) {
        for (char c : s) {
            TrieNode* node = tree.root;
            for (char* ch : node->children) {
                if (node->path.find(ch) == string::npos) {
                    node->children.push_back(TrieNode());
                }
            }
            node->path += ch;
            tree.root = node;
        }
        // 标记终止字符
        node->isEnd = false;
        for (char c : s) {
            TrieNode* node = tree.root;
            for (char* ch : node->children) {
                if (node->path.find(ch) == string::npos) {
                    node->children.push_back(TrieNode());
                }
            }
            node->path += ch;
            tree.root = node;
        }
    }

    // 查找字符串
    string search(string s) {
        string result;
        TrieNode* node = root;
        for (char c : s) {
            for (char* ch : node->children) {
                if (node->path.find(ch) != string::npos) {
                    node = node->children[ch];
                    if (node->isEnd) {
                        result.push_back(ch);
                        node = node->parent;
                    }
                }
            }
        }
        return result.empty() ? "无匹配" : result;
    }

    // 去重并排序
    void optimize() {
        sort(root->children.begin(), root->children.end());
        for (auto& child : root->children) {
            for (auto* ch : child->children) {
                if (child->path.find(ch) != string::npos) {
                    child->children[ch] = child->children[ch]->parent;
                }
            }
        }
    }

};

示例:在数据库缓存管理中的应用

假设我们有一个数据库,记录了用户最近的缓存请求。每个缓存请求是一个字符串,可能包含重复字符。使用Trie树可以高效查找最近的缓存,从而减少数据库访问次数。

以下是示例代码如何在数据库中使用Trie树进行缓存管理:

cpp
int main() {
int databasesize = 1000;
string buffer[database
size];
int buffer_idx = 0;

// 读取缓存数据
while (database_idx < database_size) {
    string query;
    char* ptr = buffer[database_idx++];
    while (true) {
        ptr += (char*)(ptr + 1);
        if (ptr >= 0) {
            buffer[database_idx] = *ptr;
            break;
        }
        // 读取空指针
        if (ptr == 0) {
            // 停止读取
            break;
        }
    }
    // 保存查询
    buffer[database_idx] = query;

    // 建立Trie树
    TrieTree tree(buffer[database_idx]);
    tree.build(tree.root, buffer);

    // 查找最近的缓存
    string result = tree.search(query);
    if (!result.empty()) {
        database_idx++;
    }
}

return 0;

}


结论

picture loss