[英]How to compute the sum and the total number of nodes in a Binary Search Tree?
I am trying to figure out a way to compute the sum and the total number of nodes in a BST, Binary Search Tree.我试图找出一种方法来计算 BST 二叉搜索树中节点的总和和总数。 I assume that the values of the nodes are all numerical.我假设节点的值都是数字的。 I have made the following code and tried different ways, but everything leads up to missing root or similar missing things.我制作了以下代码并尝试了不同的方法,但一切都会导致丢失根或类似的丢失的东西。
class BinarySearchTree:
def __init__(self, value=None):
self.value = value
if self.value:
self.left_child = BinarySearchTree()
self.right_child = BinarySearchTree()
else:
self.left_child = None
self.right_child = None
def is_empty(self):
return self.value is None
def insert(self, value):
if self.is_empty():
self.value = value
self.left_child = BinarySearchTree()
self.right_child = BinarySearchTree()
elif value < self.value:
self.left_child.insert(value)
elif value > self.value:
self.right_child.insert(value)
def compute_sum(self):
#Here I should make a function to compute the sum of all the node values in the BST.
return "Not Implemented"
def compute_count(self):
#Here I should make a function to compute the total number of nodes in the BST.
return "Not Implemented"
def main():
my_tree = BinarySearchTree()
my_tree.insert(2)
my_tree.insert(4)
my_tree.insert(6)
my_tree.insert(8)
my_tree.insert(10)
print('sum:', my_tree.compute_sum())
print('number of nodes:', my_tree.compute_count())
if __name__ == "__main__":
main()
please no hate (: Everyone has been a beginner before.请不要讨厌(:每个人以前都是初学者。
Update code to the following.将代码更新为以下内容。
class BinarySearchTree:
def __init__(self, value=None):
self.value = value
if self.value:
self.left_child = BinarySearchTree()
self.right_child = BinarySearchTree()
else:
self.left_child = None
self.right_child = None
def is_empty(self):
return self.value is None
def insert(self, value):
if self.is_empty():
self.value = value
self.left_child = BinarySearchTree()
self.right_child = BinarySearchTree()
elif value < self.value:
self.left_child.insert(value)
elif value > self.value:
self.right_child.insert(value)
def compute_sum(self):
' compute the sum of all the node values in the BST '
if self.value is None:
return 0 # No nodes
else:
# current plus sum of child nodes
return self.value + self.left_child.compute_sum() + self.right_child.compute_sum()
def compute_count(self):
' compute the total number of nodes in the BST '
if self.value is None:
return 0 # No nodes
else:
# One for current plus count of child nodes
return 1 + self.left_child.compute_count() + self.right_child.compute_count()
def main():
my_tree = BinarySearchTree()
my_tree.insert(2)
my_tree.insert(4)
my_tree.insert(6)
my_tree.insert(8)
my_tree.insert(10)
print('sum:', my_tree.compute_sum())
print('number of nodes:', my_tree.compute_count())
if __name__ == "__main__":
main()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.