简体   繁体   中英

How to make depth search in Trie?

I wrote my Trie solution, where I used defaultdict . The task is to find all words with prefix. The format must be like {of:[of, offten, offensive]}

Here my Trie class:

from collections import defaultdict

def _trie():
    return defaultdict(_trie)

TERMINAL = None

class Trie(object):
    def __init__(self):
        self.trie = _trie()

    def addWord(self, word):
        trie = self.trie
        for letter in word:
            trie = trie[letter]
        trie[TERMINAL]


    def search(self, word, trie=None):
        if trie is None:
            trie = self.trie
        for i, letter in enumerate(word):
            if letter in trie:
                trie = trie[letter]
            else:
                return False
        return trie

Here The example:

Trie = Trie()
Trie.addWord('of')
Trie.addWord('often')
Trie.addWord('offensive')


string = 'of'
s = dict(Trie.search(string))

They give the result: 在此处输入图片说明

Here I make depth searh

from collections import defaultdict
class TrieNode:
def __init__(self):
    self.child = defaultdict(TrieNode)
    self.is_word = False
    self.words = ""

class Trie:
def __init__(self):
    self.root = TrieNode()

def insert(self, word):
    cur = self.root
    for i in range(len(word)):
        cur = cur.child[word[i]]
        cur.words = word[:i+1]
    cur.is_word = True

def search(self, word):
    cur = self.root
    for char in word:
        cur = cur.child.get(char)
        if not cur:
            return []
    stack = [cur]
    res = []
    while stack:
        node = stack.pop()
        if node.is_word:
            res.append(node.words)
        for key, val in node.child.items():
            stack.append(val)
    return sorted(res)

Trie = Trie()
Trie.insert('of')
Trie.insert('often')
Trie.insert('offensive')
Trie.insert('offensive2')

Trie.search('o')

# ['of', 'offensive', 'offensive2', 'often']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM