首页 > 代码库 > 字典树(Trie)的基本实现(C++)

字典树(Trie)的基本实现(C++)

简要说明一下:

主要实现了两个操作,get,set

get用来查找字符串键值对应的value,set则用来向字典树添加key-value对。

这个实现参考自Algorithms 4th Edition, Robert Sedgewick

 

const int inf = -(1 << 30);struct Node{    int val;    Node** next;    Node(){        val = -(1 << 30);        next = new Node*[256];        for (int i = 0; i < 256; i++)            next[i] = NULL;    }};class Tries{private:    Node* root;    Node* get(Node* root, string key, int d)    {        if (root == NULL)            return NULL;        if (d == key.size())            return root;        return get(root->next[key[d]], key, d + 1);    }    Node* set(Node* root, string key, int val, int d)    {        if (root == NULL)            root = new Node();        if (d == key.length())        {            root->val = val;            return root;        }                    root->next[key[d]] = set(root->next[key[d]], key, val, d + 1);        return root;    }public:    Tries():root(NULL){  }    int get(string& key)    {        Node* ans = get(root, key, 0);        if (ans == NULL)            return inf;        return ans->val;    }    void set(string &key, int val)    {        root = set(root, key, val, 0);    }};

  

字典树(Trie)的基本实现(C++)