LeetCode-208 Implement Trie (Prefix Tree)
题目描述
Implement a trie with insert
, search
, and startsWith
methods.
题目大意
实现对一棵树的插入、搜索以及前序查找操作。
(树的每个节点代表一个小写字母,从根节点到叶节点代表一个完整的单词)
示例
E
解题思路
感谢Leetcode@cxq1992提供的思路,采用较为工程化的方法完成树结点的记录保存与操作。
复杂度分析
时间复杂度:O(NULL)
空间复杂度:O(NULL)
代码
class node { public: node() : val(' '), end(false), shared(0) {} node(char c) : val(c), end(false), shared(0) {} node* subchild(char c) { if(!child.empty()) { for(auto chi : child) { if(chi->val == c) return chi; } } return NULL; } ~node() { for(auto chi : child) delete chi; } //该树结点所保存的小写字母 char val; //该结点是否是叶节点 bool end; //子节点的个数 int shared; //子节点保存 vector<node*> child; }; class Trie { public: /** Initialize your data structure here. */ Trie() { root = new node(); } /** Inserts a word into the trie. */ void insert(string word) { if(search(word)) return; node* cur = root; for(char c : word) { node* tmp = cur->subchild(c); if(tmp == NULL) { tmp = new node(c); cur->child.push_back(tmp); cur = tmp; } else { cur = tmp; } ++cur->shared; } cur->end = true; } /** Returns if the word is in the trie. */ bool search(string word) { node* tmp = root; for(char c : word) { tmp = tmp->subchild(c); if(tmp == NULL) return false; } return tmp->end; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(string prefix) { node* tmp = root; for(char c : prefix) { tmp = tmp->subchild(c); if(tmp == NULL) return false; } return true; } private: node* root; }; /** * Your Trie object will be instantiated and called as such: * Trie* obj = new Trie(); * obj->insert(word); * bool param_2 = obj->search(word); * bool param_3 = obj->startsWith(prefix); */