トライ(接頭辞木)は、各辺が文字を表し、ルートからのパスが接頭辞を綴る木です。接頭辞を共有する単語は同じパスを共有するため、接頭辞検索が非常に高速になります。
構造
text
Insert "cat", "car", "dog":
root
/ \
c d
| |
a o
/ \ |
t* r* g* (* marks end-of-word)
コード
python
:
():
.children = {}
.is_end =
:
():
.root = TrieNode()
():
node = .root
ch word:
node = node.children.setdefault(ch, TrieNode())
node.is_end =
():
node = .root
ch prefix:
ch node.children:
node = node.children[ch]
