我有一个二进制搜索树,其中包含文件中的单词,现在我想从中搜索一个单词,它应该返回该单词的长度和出现次数。我不知道如何从根开始,如何从那里开始。一些例子的一点解释将非常感激。
我已附上我当前的代码:
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()
答案 0 :(得分:1)
请注意,添加到BST涉及搜索应该的值,然后将其放在那里;所以,如果你可以建立一个,你应该能够搜索一个。
答案 1 :(得分:0)
我这样做了,好像做了那件事
def search(tree, word):
node = tree
depth = 0
count = 0
while True:
print(node.value)
depth += 1
if node.value == word:
count = node.count
break
elif word < node.value:
node = node.left
elif word > node.value:
node = node.right
return depth, count
def main():
print(search(tree, "a"))