Skip to content

Commit 705a2ea

Browse files
committed
Handle more edge cases for Delete()
We should never merge into the root node since it's assumed to be the empty string. We need to check for deleting this node from the parent before we have potentially merged the node and its child. If we check after we've merged, it might be the case that the merged node has no children (in which case we don't want to delete it from the parent, since it's still a valid entry.) This patch includes tests to check that we're handling these cases.
1 parent 93351ac commit 705a2ea

File tree

2 files changed

+27
-8
lines changed

2 files changed

+27
-8
lines changed

‎radix.go‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -275,18 +275,19 @@ DELETE:
275275
n.leaf = nil
276276
t.size--
277277

278+
// Check if we should delete this node from the parent
279+
if parent != nil && len(n.edges) == 0 {
280+
parent.delEdge(label)
281+
}
282+
278283
// Check if we should merge this node
279-
if len(n.edges) == 1 {
284+
if n != t.root && len(n.edges) == 1 {
280285
n.mergeChild()
281286
}
282287

283-
// Check if we should merge or delete this node
284-
if parent != nil {
285-
if len(n.edges) == 0 {
286-
parent.delEdge(label)
287-
} else if len(parent.edges) == 1 && !parent.isLeaf() {
288-
parent.mergeChild()
289-
}
288+
// Check if we should merge the parent's other child
289+
if parent != nil && parent != t.root && len(parent.edges) == 1 && !parent.isLeaf() {
290+
parent.mergeChild()
290291
}
291292

292293
return leaf.val, true

‎radix_test.go‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,24 @@ func TestRoot(t *testing.T) {
8686
}
8787
}
8888

89+
func TestDelete(t *testing.T) {
90+
91+
r := New()
92+
93+
s := []string{"", "A", "AB"}
94+
95+
for _, ss := range s {
96+
r.Insert(ss, true)
97+
}
98+
99+
for _, ss := range s {
100+
_, ok := r.Delete(ss)
101+
if !ok {
102+
t.Fatalf("bad %q", ss)
103+
}
104+
}
105+
}
106+
89107
func TestLongestPrefix(t *testing.T) {
90108
r := New()
91109

0 commit comments

Comments
 (0)