我正在尝试查找处于BST相同级别的所有节点的总和。但是我的count_sum和total_elements_at_level变量没有更新。我知道这很愚蠢,但是我无法理解。正在输出0。
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def find_average_at_level(self, level):
current = self.root
current_level = 1
total_elements_at_level = 0
current_sum = 0
self.find_average_helper(current, current_level, level, current_sum, total_elements_at_level)
return current_sum / total_elements_at_level
def find_average_helper(self, current, current_level, level, current_sum, total_elements_at_level):
if current:
current_level += 1
if current_level == level:
current_sum += current.value
total_elements_at_level += 1
else:
self.find_average_helper(current.left, current_level, level, current_sum, total_elements_at_level)
self.find_average_helper(current.right, current_level, level, current_sum, total_elements_at_level)
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
#print tree.search(4)
# Should be False
#print(tree.search(6))
print(tree.find_average_at_level(3))