前缀树python实现

#File Name : 前缀树.py

class TrieNode(object):
    def __init__(self):
        self.path = 0
        #路过此节点几个
        self.end = 0
        #以此为结尾的几个
        self.map = [None for i in range(26)]
        #每一个节点有26条路

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

    def insert(self,word):
        if word == None:
            return
        node = self.root
        for i in word:
            index = ord(i) - ord('a')
            #ord 为阿斯科码
            if node.map[index] == None:
                node.map[index] = TrieNode()
            node = node.map[index]
            node.path += 1
        node.end+=1
        print('insert successful !!!')

    def search(self,word):
        if word == None:
            return 0
        node = self.root
        for i in word:
            index = ord(i)-ord('a')
            if node.map[index]==None:
                return 0
            node = node.map[index]
        return node.end
        # 如何区分 ‘be’ ,‘bef’
        # 返回插入几次

    def delete(self,word):
        if self.search(word) != 0:
            node = self.root
            for i in word:
                index = ord(i)-ord('a')
                node.map[index].path -=1
                if node.map[index].path==0:
                    #本来原来就有一个  再删一个 就没了
                    #变成0 代表不需要此节点了
                    node.map[index] = None
                    return
                node = node.map[index]
            node.end-=1
# 不要把字母放到节点上
def prefixNumber(self,pre):
    if pre == None:
        return
    node = self.root
    for i in pre:
        index = ord(i)-ord('a')
        if node.map[index] == None:
            return 0
        node = node.map[index]
    return node.path

 

你可能感兴趣的:(算法牛人之路)