trie 树的简单实现

来源:互联网 发布:杭州锐智软件 编辑:程序博客网 时间:2024/06/06 13:26
namespace trie {    class trieNode {    public:        trieNode() : nodeSize(0) {             for(int i = 0; i < 26; ++i) children[i] = NULL;         }        ~trieNode() {            for(int i = 0; i < 26; ++i) {                delete children[i];                children[i] = NULL;            }        }    public:        int nodeSize;          trieNode* children[26];      };    void trieInsert(string& a, trieNode* root) {        if (root == NULL) return;        int j = 0;        while(j < a.size()) {            if (root->children[a[j] - 'a'] == NULL) {                root->children[a[j] - 'a'] = new trieNode();            }            root = root->children[a[j] - 'a'];            j++;        }        root->nodeSize += 1;    }    void trieDelete(string& a, trieNode* root) {        if (root == NULL) return;        int j = 0;        while (j < a.size()) {            if (root->children[a[j] - 'a'] == NULL) {                return;            }            root = root->children[a[j] - 'a'];            j++;        }        if (root) root->nodeSize -= 1;    }    bool trieFind(string& a, trieNode* root) {        if (root == NULL) return false;        int j = 0;        while (j < a.size()) {            int t = a[j] - 'a';            if (root->children[t] == NULL) {                return false;            }            root = root->children[t];            j++;        }        return root->nodeSize != 0;    }};
0 0
原创粉丝点击