| 7 | |
| 8 | |
| 9 | class TrieNode: |
| 10 | def __init__(self) -> None: |
| 11 | self.nodes: dict[str, TrieNode] = {} # Mapping from char to TrieNode |
| 12 | self.is_leaf = False |
| 13 | |
| 14 | def insert_many(self, words: list[str]) -> None: |
| 15 | """ |
| 16 | Inserts a list of words into the Trie |
| 17 | :param words: list of string words |
| 18 | :return: None |
| 19 | """ |
| 20 | for word in words: |
| 21 | self.insert(word) |
| 22 | |
| 23 | def insert(self, word: str) -> None: |
| 24 | """ |
| 25 | Inserts a word into the Trie |
| 26 | :param word: word to be inserted |
| 27 | :return: None |
| 28 | """ |
| 29 | curr = self |
| 30 | for char in word: |
| 31 | if char not in curr.nodes: |
| 32 | curr.nodes[char] = TrieNode() |
| 33 | curr = curr.nodes[char] |
| 34 | curr.is_leaf = True |
| 35 | |
| 36 | def find(self, word: str) -> bool: |
| 37 | """ |
| 38 | Tries to find word in a Trie |
| 39 | :param word: word to look for |
| 40 | :return: Returns True if word is found, False otherwise |
| 41 | """ |
| 42 | curr = self |
| 43 | for char in word: |
| 44 | if char not in curr.nodes: |
| 45 | return False |
| 46 | curr = curr.nodes[char] |
| 47 | return curr.is_leaf |
| 48 | |
| 49 | def delete(self, word: str) -> None: |
| 50 | """ |
| 51 | Deletes a word in a Trie |
| 52 | :param word: word to delete |
| 53 | :return: None |
| 54 | """ |
| 55 | |
| 56 | def _delete(curr: TrieNode, word: str, index: int) -> bool: |
| 57 | if index == len(word): |
| 58 | # If word does not exist |
| 59 | if not curr.is_leaf: |
| 60 | return False |
| 61 | curr.is_leaf = False |
| 62 | return len(curr.nodes) == 0 |
| 63 | char = word[index] |
| 64 | char_node = curr.nodes.get(char) |
| 65 | # If char not in current trie node |
| 66 | if not char_node: |