Prefix Tree

Creating a prefix tree is quite easy in Python!

root = {}

def addToTree(node, word=()):
        if not word: return

        addToTree(node.setdefault(word[0], {}), word[1: ])

def main():
        for word in ('batman', 'bane', 'bale',):
                addToTree(root, word)
        print root

Output:

{'b': {
        'a': {
            'l': {
                'e': {}
                 }, 
            'n': {
                'e': {}
                 }, 
            't': {
                'm': {
                    'a': {
                        'n': {}
                         }
                     }
                 }
             }
       }
}

leave your comment