压缩Radix Trie实战:新单词停在一条边中间,为什么必须先拆开标签
树里已经有carpet,再插入car,前三个字符虽然都对上了,查询却停在原先整条carpet边的中间。若只在原节点上加一个标记,便无法表达car究竟在哪里结束;正确操作是把边拆成car和pet,让新增中间节点承担词尾。
本文实现字符级压缩Radix集合:边保存一段非空字符串,节点另存是否为完整键的终止标记。支持插入、精确查询和删除,接受最多128个Unicode码点的str,包括空字符串;重复插入不增加份数。
AI模型生成的概念插图:连续轨道在共享段末端分叉,另一组短轨道合成单段,表达压缩边的拆分与合并;非精确树结构或实测截图。
完整程序与实际输出
保存以下完整源码为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码为0,标准错误为空。仅使用标准库与内存教学数据,不需要安装依赖或访问网络。
from itertools import product
from random import Random
class Node:
def __init__(self, terminal=False):
self.terminal = terminal
self.edges = {}
def check_word(word):
if type(word) is not str or len(word) > 128:
raise ValueError("str of at most 128 code points required")
class RadixSet:
def __init__(self):
self.root = Node()
def add(self, word):
check_word(word)
node, pos = self.root, 0
while pos < len(word):
first = word[pos]
if first not in node.edges:
node.edges[first] = (word[pos:], Node(True))
return
label, child = node.edges[first]
size = 0
while (size < len(label) and pos + size < len(word)
and label[size] == word[pos + size]):
size += 1
if size == len(label):
node, pos = child, pos + size
continue
middle = Node(pos + size == len(word))
middle.edges[label[size]] = (label[size:], child)
if pos + size < len(word):
rest = word[pos + size:]
middle.edges[rest[0]] = (rest, Node(True))
node.edges[first] = (label[:size], middle)
return
node.terminal = True
def contains(self, word):
check_word(word)
node, pos = self.root, 0
while pos < len(word):
edge = node.edges.get(word[pos])
if edge is None or not word.startswith(edge[0], pos):
return False
label, node = edge
pos += len(label)
return node.terminal
def discard(self, word):
check_word(word)
node, pos, path = self.root, 0, []
while pos < len(word):
first = word[pos]
edge = node.edges.get(first)
if edge is None or not word.startswith(edge[0], pos):
return False
path.append((node, first))
label, node = edge
pos += len(label)
if not node.terminal:
return False
node.terminal = False
for parent, first in reversed(path):
label, child = parent.edges[first]
if not child.terminal:
if not child.edges:
del parent.edges[first]
elif len(child.edges) == 1:
tail, grandchild = next(iter(child.edges.values()))
parent.edges[first] = (label + tail, grandchild)
return True
def words(self):
result = []
def visit(node, prefix):
if node.terminal:
result.append(prefix)
if node is not self.root and not node.terminal:
assert len(node.edges) >= 2
for first, (label, child) in node.edges.items():
assert label and label[0] == first
visit(child, prefix + label)
visit(self.root, "")
return sorted(result)
tree = RadixSet()
for word in ("carpet", "car", "carbon", "cat", "", "car"):
tree.add(word)
print("stored:", tree.words())
print("car / carp / carpet:", [tree.contains(w) for w in ("car", "carp", "carpet")])
print("remove car:", tree.discard("car"), tree.words())
print("remove absent carp:", tree.discard("carp"))
single = RadixSet()
for word in ("carpet", "car"):
single.add(word)
single.discard("car")
print("merged root edge:", single.root.edges["c"][0])
universe = ["".join(x) for n in range(5) for x in product("ab", repeat=n)]
rng, reference, sample = Random(67), set(), RadixSet()
checks = 0
for _ in range(600):
word = rng.choice(universe)
if rng.randrange(2):
sample.add(word)
reference.add(word)
else:
assert sample.discard(word) == (word in reference)
reference.discard(word)
assert sample.words() == sorted(reference)
for query in universe:
assert sample.contains(query) == (query in reference)
checks += 1
print("set-oracle membership checks:", checks)
for word in ("山海", "山", "山河"):
sample.add(word)
assert sample.discard("山") and not sample.contains("山")
assert sample.contains("山海") and sample.contains("山河")
print("Unicode prefix deletion: passed")
for bad in (b"car", "x" * 129):
try:
tree.add(bad)
except ValueError as error:
print("rejected:", error)
else:
raise AssertionError("invalid word accepted")以下为上面程序的实际标准输出,仅供核对,不是需要再次执行的命令:
stored: ['', 'car', 'carbon', 'carpet', 'cat'] car / carp / carpet: [True, False, True] remove car: True ['', 'carbon', 'carpet', 'cat'] remove absent carp: False merged root edge: carpet set-oracle membership checks: 18600 Unicode prefix deletion: passed rejected: str of at most 128 code points required rejected: str of at most 128 code points required
压缩的是没有分歧的路径
普通字符Trie可以每个字符占一条边。连续节点若只有一个孩子,而且中间没有完整单词结束,就可以把这些边的标签连接起来。carpet独自存在时,根只需一条carpet边;加入cat以后,共用ca,随后分成rpet与t。
每个节点用首字符索引孩子。同一节点的两条边不允许以相同字符开头,否则只看下一字符无法决定走哪条。边标签始终非空,根不携带入边;空字符串是否存在,直接由根的terminal表示。
一个公共前缀,分出三种插入情况
沿现有边比较时,size记录标签与新键剩余部分的公共前缀长度。若整条标签都匹配,就下降到孩子继续处理;若找不到同首字符的边,把全部剩余字符直接作为一条新边。
剩下的情况就是边中间发生分歧。程序创建middle,把旧边剩余标签连向原孩子,把新键剩余标签连向新终止节点。父边只保留公共部分。旧孩子连同其后代整体保留,不重新插入这些单词。
新键可能刚好在分裂位置结束。例如已有carpet,再加入car,middle自己成为终止节点,下面只保留pet边。终止节点可以只有一个孩子:把它压掉会让car这个完整键消失。这正是不能机械删除所有单子节点的原因。
走完查询,不等于找到了完整单词
contains要求每一条经过的边标签全部匹配,最后还要检查terminal。存有car与carpet时,car能在终止节点结束;carp停在pet边内部,不能算命中,即使它确实是某个键的前缀。
代码用startswith(label,pos)核对完整标签,并把pos增加标签长度。查询没有经过任何边时,也按同一规则检查根的终止标记,所以空字符串并非特殊的假值或缺失结果。前缀补全需要不同接口,本文没有把它混进精确存在性查询。
删除先撤销词尾,再向上清理
discard先走完整路径,并把沿途父节点与首字符保存下来。路径不存在、标签未完整匹配、最终节点没有终止标记,都会返回False且不改树。只有确实找到完整键时,才清掉terminal。
随后逆序查看路径:非终止孩子若没有后代,父边可以删除;若只剩一条边,就把父边标签和孩子的唯一边标签连接,直接接到孙节点。孩子仍然是完整键,或者有两条以上分支时,则保留它。
删除car不能删掉carbon和carpet,样本输出会直接展示这点。另一棵只含car和carpet的小树,在删去car后,根边会重新变成carpet。清理根的空串标记不会移除非空键,因为根没有需要拼接的入边。
用集合判结果,用结构规则判压缩
固定种子操作序列从31个长度零到四的ab字符串中选择600次插入或删除。每次更新以后,都把全部31个候选的contains结果与Python集合比较,共18600次;删除的布尔返回值也与操作前的成员关系核对。
words通过遍历边重新拼出当前所有完整键,同时断言非根、非终止节点至少有两个孩子,且首字符索引与实际非空标签一致。集合只证明可见内容正确,结构断言还会抓到已经能压缩却遗留的冗余单子节点。
单独样本覆盖重复插入、空键、前缀键删除、边内不存在键、中文前缀,以及bytes和超长输入被拒绝。有限随机序列不是全部操作历史的证明,前面关于路径保留与三种局部清理的论证仍然不可少。
节点更少,标签字符仍然需要存储
一次查询访问的标签总长度不超过输入键长度k,按字典查询的通常平均模型计算为O(k)。插入需要比较路径并复制少量拆分标签;删除还会创建合并后的字符串,复制成本取决于被拆分或合并标签的长度,不能把Python字符串拼接当成零成本。
树的分支与终止节点数量和不同键数同阶,但所有标签内容总量仍应单独计入。words为检查生成所有单词,还需要输出总字符数对应的时间和空间;它不是常数成本的调试开关。代码的128码点限制约束单键深度,没有限制集合总容量。
本例完整保存并比较压缩标签,因此不会仅凭跳过的分支位就宣告相等。所引CMU课件还讨论只保留部分辨别信息的数据库实现需要回原记录核对;那种表示的误报边界不能直接套到这里。本文也不做Unicode规范化或大小写折叠,字符相等按Python原值判断。
参考资料
一手资料及本地运行核查日期:2026年10月7日。程序、教学样本和校验代码为本文独立编写;结果只证明所述样本与不变式检查,不代表真实业务性能。


