From 0d76834295d1f64dd34765d56abc22143c3a0996 Mon Sep 17 00:00:00 2001 From: dhairya Date: Sat, 3 Oct 2026 03:21:01 +0530 Subject: [PATCH] Preserve the radix tree root when deleting a branch --- data_structures/trie/radix_tree.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_structures/trie/radix_tree.py b/data_structures/trie/radix_tree.py index 11e0dc23faa9..0a38940475f0 100644 --- a/data_structures/trie/radix_tree.py +++ b/data_structures/trie/radix_tree.py @@ -167,8 +167,8 @@ def delete(self, word: str) -> bool: # We delete the nodes if no edges go from it if len(incoming_node.nodes) == 0: del self.nodes[word[0]] - # We merge the current node with its only child - if len(self.nodes) == 1 and not self.is_leaf: + # Merge non-root nodes with their only child. + if self.prefix and len(self.nodes) == 1 and not self.is_leaf: merging_node = next(iter(self.nodes.values())) self.is_leaf = merging_node.is_leaf self.prefix += merging_node.prefix