写一段 trie树代码
时间: 2023-02-19 07:20:45 浏览: 71
Trie 树实现的源码
这是一段基于 Python 的 trie 树的代码:
```
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_word
def starts_with(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
```
这个 trie 树的实现包含了三个操作:插入单词,搜索单词以及搜索前缀。
阅读全文