简体   繁体   中英

Trie Implementation in Python -- Print Keys

I Implemented a Trie data structure using python, now the problem is it doesn't display the keys that Trie is stored in its data structure.

class Node:
    def __init__(self):
        self.children = [None] * 26
        self.endOfTheWord = False

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

    def getNode(self):
        return Node()

    def charToIndex(self ,ch):
        return ord(ch) - ord('a')             

    def insert(self ,word):
        current = self.root
        for i in range(len(word)):
            index = self.charToIndex(word[i])

            if current.children[index] is None:
                current.children[index] = self.getNode()

            current = current.children[index]

        current.endOfTheWord = True

    def printKeys(self):
        str = []
        self.printKeysUtil(self.root ,str)

    def printKeysUtil(self ,root ,str):

        if root.endOfTheWord == True:
            print(''.join(str))
            return

        for i in range(26):

            if root.children[i] is not None:
                ch = chr(97) + chr(i)
                str.append(ch)
                self.printKeysUtil(root.children[i] ,str)
                str.pop()

您可以执行节点的预排序遍历,无论您在何处找到词尾标记,都可以放大到根部,边走边捕捉字母,以获得完整的词……除了为此,您需要在每个节点中存储父节点。

def printKeysUtil(self ,root ,str):

        if root.endOfTheWord == True:
            print(''.join(str))
            return

        for i in range(26):

            if root.children[i] is not None:
                ch = chr(97+i)
                str.append(ch)
                self.printKeysUtil(root.children[i] ,str)
                str.pop()

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