Last active
September 22, 2022 04:51
-
-
Save theabbie/2d009701a6712acf066c36b490e7e3c4 to your computer and use it in GitHub Desktop.
TrieMap implementation in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, val = None): | |
self.left = None | |
self.right = None | |
self.val = val | |
self.end = False | |
class TrieMap: | |
def __init__(self): | |
self.root = Node() | |
def set(self, key, val): | |
curr = self.root | |
while key: | |
if key & 1: | |
if curr.right == None: | |
curr.right = Node() | |
curr = curr.right | |
else: | |
if curr.left == None: | |
curr.left = Node() | |
curr = curr.left | |
key = key >> 1 | |
curr.val = val | |
curr.end = True | |
def get(self, key): | |
curr = self.root | |
while key: | |
if curr == None: | |
return None | |
if key & 1: | |
curr = curr.right | |
else: | |
curr = curr.left | |
key = key >> 1 | |
if not curr or not curr.end: | |
return None | |
return curr.val | |
tmap = TrieMap() | |
tmap.set(41, "Hello World") | |
print(tmap.get(41)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment