Skip to content

add merge function for trie #7964

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions data_structures/trie/trie.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
making it impractical in practice. It however provides O(max(search_string, length of
longest word)) lookup time making it an optimal approach when space is not an issue.
"""
from __future__ import annotations


class TrieNode:
Expand Down Expand Up @@ -33,6 +34,21 @@ def insert(self, word: str) -> None:
curr = curr.nodes[char]
curr.is_leaf = True

def merge(self, trie_node: TrieNode) -> None:
"""
Merge the current instance of TrieNode with the passed instance.
:param trie_node: the source to be merged.
"""

for source_node in trie_node.nodes:
if source_node not in self.nodes:
self.nodes[source_node] = TrieNode()

self.nodes[source_node].merge(trie_node.nodes[source_node])

if trie_node.is_leaf:
self.is_leaf = True

def find(self, word: str) -> bool:
"""
Tries to find word in a Trie
Expand Down Expand Up @@ -105,6 +121,16 @@ def test_trie() -> bool:
root.delete("banana")
assert not root.find("banana")
assert root.find("bananas")

assert not root.find("new_merged_word")
assert not root.find("new_merged_word2")
node_to_merge = TrieNode()
node_to_merge.insert_many(["new_merged_word", "new_merged_word2"])
root.merge(node_to_merge)
assert root.find("new_merged_word")
assert root.find("new_merged_word2")
assert root.find("bananas")

return True


Expand Down