c++实现trie树

31 阅读1分钟

下面是一个简单的C++实现Trie树的示例:

#include <iostream>
#include <unordered_map>

class TrieNode {
public:
    std::unordered_map<char, TrieNode*> children;
    bool isEnd;

    TrieNode() : isEnd(false) {}
};

class Trie {
private:
    TrieNode* root;

public:
    Trie() {
        root = new TrieNode();
    }

    // 向Trie树中插入一个单词
    void insert(const std::string& word) {
        TrieNode* node = root;
        for (char ch : word) {
            if (!node->children[ch]) {
                node->children[ch] = new TrieNode();
            }
            node = node->children[ch];
        }
        node->isEnd = true;
    }

    // 检查一个单词是否在Trie树中
    bool search(const std::string& word) {
        TrieNode* node = root;
        for (char ch : word) {
            if (!node->children[ch]) {
                return false;
            }
            node = node->children[ch];
        }
        return node->isEnd;
    }

    // 检查一个前缀是否在Trie树中
    bool startsWith(const std::string& prefix) {
        TrieNode* node = root;
        for (char ch : prefix) {
            if (!node->children[ch]) {
                return false;
            }
            node = node->children[ch];
        }
        return true;
    }
};

int main() {
    Trie trie;

    trie.insert("apple");
    std::cout << "Search 'apple': " << std::boolalpha << trie.search("apple") << std::endl;
    std::cout << "Search 'app': " << std::boolalpha << trie.search("app") << std::endl;
    std::cout << "StartsWith 'app': " << std::boolalpha << trie.startsWith("app") << std::endl;

    return 0;
}

在这个示例中,TrieNode 类表示Trie树中的节点,Trie 类表示Trie树本身。TrieNode 类中有一个哈希表用于存储子节点,Trie 类中有一个指向根节点的指针。insert() 方法用于向Trie树中插入一个单词,search() 方法用于检查一个单词是否在Trie树中,startsWith() 方法用于检查一个前缀是否在Trie树中。