I have a binary search tree with words from a file and now I'd like to search a word from it and it should return the length and how many times this word has occurred. I'm not sure how to start from the root and how to proceed from there. a little explanation with some examples would be much appreciated.
I have attached my current code:
class Node:
def __init__(self, value, left=None, right=None):
self.left = left
self.right = right
self.value = value
self.count = 1
def add(self, value):
if self.value == value:
self.count += 1
elif value < self.value:
if self.left is None:
self.left = Node(value)
else:
self.left.add(value)
else:
if self.right is None:
self.right = Node(value)
else:
self.right.add(value)
def printTree(self):
if self.left is not None:
self.left.printTree()
print(str(self.value) + " " + str(self.count))
if self.right is not None:
self.right.printTree()
def processFileContent(file):
words = []
for line in file:
unprocessedWords = re.split(" ", line)
for word in unprocessedWords:
word = word.lower()
if word.isalpha():
words.append(word)
return words
def processFile():
file = open("text.txt", "r")
words = processFileContent(file)
file.close()
return words
def createTree(words):
if len(words) > 0:
tree = Node(words[0])
for word in words:
tree.add(word)
return tree
else:
return None
def main():
words = processFile()
tree = createTree(words)
tree.printTree()