Python前缀树删除操作怎么实现并回收内存?

山间有风
山间有风
发布时间:2026-12-06 | 855人浏览过
原创

在 Python 中实现前缀树( Trie )的删除操作,核心在于为每个节点维护一个 children_count 计数器。当某个子节点的计数降为 0 时,立即从父节点的字典中移除该键并释放引用,从而实现内存回收。

Python前缀树删除操作怎么实现并回收内存?

前缀树节点结构与删除逻辑

前缀树的每个节点通常包含指向子节点的字典和标记单词结束的布尔值。为了实现安全的内存回收,我们需要在节点中增加一个字段来记录当前有多少个单词经过或结束于该节点。

Python前缀树删除操作怎么实现并回收内存?

在插入新单词时,路径上所有节点的计数器加 1;删除单词时,路径上所有节点的计数器减 1。如果某个节点的计数器变为 0,说明没有任何单词使用该节点及其后续分支,此时应将该节点从父节点的 children 字典中删除。这样不仅完成了逻辑上的删除,还通过断开引用让 Python 垃圾回收器能够回收内存。

完整可运行的删除实现代码

以下代码定义了一个支持删除操作的 Trie 类。你可以将其保存为 trie_delete.py 文件,直接运行即可看到删除前后的结构变化及内存回收效果。

Python前缀树删除操作怎么实现并回收内存?

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end_of_word = False
        self.children_count = 0  # 记录经过此节点的单词数量

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

    def insert(self, word: str) -> None:
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
            node.children_count += 1
        node.is_end_of_word = True

    def delete(self, word: str) -> bool:
        def _delete(node, word, depth):
            if depth == len(word):
                if not node.is_end_of_word:
                    return False
                node.is_end_of_word = False
                # 如果该节点没有子节点且不是根节点,则可以被回收
                if node.children_count == 0:
                    return True
                return False

            char = word[depth]
            if char not in node.children:
                return False

            child_node = node.children[char]
            should_delete_child = _delete(child_node, word, depth + 1)

            if should_delete_child:
                del node.children[char]
                node.children_count -= 1
                # 如果父节点也没有子节点且不是根节点,继续向上回收
                if node.children_count == 0 and depth > 0:
                    return True
            else:
                node.children_count -= 1

            return False

        if not word or not self.root.children:
            return False
        return _delete(self.root, word, 0)

# 测试用例
trie = Trie()
trie.insert("apple")
trie.insert("app")
print("Before deletion:", trie.root.children.get('a').children.get('p').children.get('p').is_end_of_word)

result = trie.delete("app")
print(f"Delete 'app' result: {result}")
print("After deletion, 'app' is end of word:", trie.root.children.get('a').children.get('p').children.get('p').is_end_of_word)
print("After deletion, 'apple' still exists:", trie.root.children.get('a').children.get('p').children.get('p').children.get('l').is_end_of_word)

运行程序后,先打印出插入 "app" 后其结尾标记为 True。删除 "app" 后,再次检查发现其结尾标记变为 False,但 "apple" 的路径依然完整存在。这证明了删除操作仅移除了目标单词的结束标记,并清理了不再被任何单词引用的节点(如 "app" 中的末尾的一个 'p' 节点),从而实现了内存的有效回收。

代码演示了如何插入多个单词,然后删除其中一个。观察输出可以发现,删除后未使用的节点已被清理,而共享的前缀部分得以保留。

处理共享前缀时的边界情况

当删除的单词与其他单词存在公共前缀时,必须确保只删除非共享部分的节点。

在上述实现中,由于我们依赖 children_count 来判断节点是否被废弃,因此即使两个单词共享前缀,只要计数器正确累加和递减,删除其中一个就不会影响另一个的路径。例如,删除 "app" 不会影响 "apple" 的存在,因为 "apple" 路径上的节点计数器不会降为 0。这种机制天然避免了误删共享节点的问题,确保了数据结构的一致性。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表