I am almost finished with a project that has us creating a dictionary class that utilizes a binary tree structure. I am however stuck on how to implement a method that prints out all the elements in the tree, I just don't have much experience with binary trees so its rather confusing on how to code it.
The method I am trying to figure out is a keys method, that will traverse the entire tree and return a list of all the keys. Someone I know has hinted that I should create a private helper function that recursively traverses the tree and keeps track of all the keys. I would like to create what is he is talking about but I have no earthly idea how to code it. Can anyone help me code this out? Figuring this out would pretty much finish it all up for me.
Here is my code so far. [Key:Value] pairs are tuples. I have coded it and also had some help from textbook examples to construct all you see here:
class DictWithTree:
def __init__(self):
self._element = None
self._left = None
self._right = None
self._size = 0
def isempty(self):
if self._element == None:
return True
return False
def __len__(self):
return self._size
def __contains__(self,key):
path = self._tracePath(key)
return path[-1]._size > 0
def _tracePath(self,key): # taken from the textbook example and modified
if len(self) == 0 or key == self._element[0]:
return [self]
elif len(key) < len(self._element[0]):
return [self] + self._left._tracePath(key)
else:
return [self] + self._right._tracePath(key)
def __getitem__(self,key):
if len(self) == 0:
raise KeyError(key)
elif key == self._element[0]:
return self._element[1]
elif key < self._element[0]:
return self._left[key]
elif key > self._element[0]:
return self._right[key]
else:
raise KeyError(key)
def __setitem__(self,key,value):
path = self._tracePath(key)
endOfPath = path[-1]
if endOfPath._element != None:
if endOfPath._element[0] == key:
endOfPath._element = key,value
if endOfPath._size == 0: # a new element
for location in path:
location._size += 1
endOfPath._element = key,value
endOfPath._left = DictWithTree()
endOfPath._right = DictWithTree()
def clear(self):
self._element = None
self._left = None
self._right = None
self._size = 0
def pop(self,key):
value = self[key]
self._remove(key)
return value
def popitem(self): # returns the 'last' item in the dictionary,
if self.isempty(): # (i.e. the largest key in the dictionary)
return KeyError("There are no keys in the dictionary")
elif self._right._element == None:
return self._element
else:
return self._right.popitem()
def _remove(self,key):
path = self._tracePath(key)
endOfPath = path[-1]
if endOfPath._size > 0:
for location in path:
location._size -= 1
if len(endOfPath._left) == 0:
endOfPath._promoteChild(endOfPath._right)
elif len(endOfPath._right) == 0:
endOfPath._promoteChild(endOfPath._left)
else:
endOfPath._element = endOfPath._left.pop()
def _promoteChild(self,child):
self._element = child._element
self._left = child._left
self._right = child._right