我的作业需要我对BST中给定值下的所有数字求和。但是,我不知道该怎么做。感谢您的帮助。
class BinarySearchTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def search(self, find_data):
if self.data == find_data:
return self
elif find_data < self.data and self.left != None:
return self.left.search(find_data)
elif find_data > self.data and self.right != None:
return self.right.search(find_data)
else:
return None
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_left(self, tree):
self.left = tree
def set_right(self, tree):
self.right = tree
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
def create_new_bst(lst):
#creates a new tree with root node 55, and then inserts all the
#remaining values in order into the BST
def sum_beneath(t, value):
# don't know how to do
t = create_new_bst([55, 24, 8, 51, 25, 72, 78])
result = sum_beneath(t, 72)
print('Sum beneath 72 =', result)# should show 'Sum beneath 72 = 78'
我是BST的新手,所以我真的不知道如何开始和做这个问题。
def insert(self, new_data):#can I just call this function in 'create_new_bst'?
if self.data:
if new_data < self.data:
if self.left is None:
self.left = BinarySearchTree(new_data)
else:
self.left.insert(new_data)
elif new_data > self.data:
if self.right is None:
self.right = BinarySearchTree(new_data)
else:
self.right.insert(new_data)
else:
self.data = data
答案 0 :(得分:0)
好的,因为这是一个练习,所以我不会填写所有内容,但是我会尽力让您了解应该如何做:
您需要通过一种简单的方法来创建树:
def create_new_bst(lst):
tree = BinarySearchTree(tree[0])
# And then, using the insert method, which is correct, add your nodes in the tree
return tree
首先,您需要找到根为72
的子树
# Replace the pass with the appropriate code
def find_subtree(tree, value):
if value == tree.data: # This is found yeah !
pass
if value > tree.data: # Ok, this is not our data, we should look recursively in one of the children (I will not tell you which one). Maybe we can use find_subtree reccursively?
pass
if value < tree.data: # Same as above, but maybe we should look in the other child
pass
raise ValueError("Not found value " + str(value)) # Nothing has been found.
现在,您发现带有my_tree = find_subtree(t, 72)
的树,您应该将左树(如果存在)和右树(如果存在)相加
def sum_beneath(t, value):
my_tree = find_subtree(t, value)
s = 0
if my_tree.left is not None:
s += my_tree.left.sum_tree()
if my_tree.right is not None:
s += my_tree.right.sum_tree()
return s
让我们定义sum_tree
方法(在类中)! :)
def sum_tree(self):
ans = self.data
# Add the left sum reccursively
# Add the right sum reccursively
return ans
我希望这将帮助您理解BST的概念。如果您需要帮助,请随时发表评论
答案 1 :(得分:0)
找到一个特定值下的节点总数是一个很有趣的问题,我们可以想到类似搜索和穿越问题,可以有多种方法来实现,但是我可以想到这样的事情-
我能想到的大O时间复杂度应该是这样的-
对于BST中第 n 个节点, log(n)应该是搜索时间,然后是横向搜索(按顺序,按顺序,按顺序或按顺序-order),则应为 mn ,其中(m为节点总数)
因此,总和为(log(n)+ m-n)〜O(M)。