Skip to content

Latest commit

 

History

History
34 lines (30 loc) · 847 Bytes

83. 构建Trie.md

File metadata and controls

34 lines (30 loc) · 847 Bytes
class TrieNode():
    def __init__(self, val=None):
        self.val = val
        self.isEnd = False
        self.children = {}
        
class Trie:
    def __init__(self):
        self.root = TrieNode()
        
    def insert(self, word):
        cur = self.root
        for c in word:
            if c not in cur.children:
                cur.children[c] = TrieNode(c)
            cur = cur.children[c]
        cur.isEnd = True
        
    def search(self, word):
        cur = self.root
        for c in word:
            if c not in cur.children:
                return False
            cur = cur.children[c]
        return cur.isEnd
    
    def delete(self, word):
        if self.search(word):
            cur = self.root
            for c in word:
                cur = cur.children[c]
            cur.isEnd = False