所以我在该程序中有一个小错误,但是我真的不知道如何解决它,如果有人可以帮助我指出它的位置,我将不胜感激。因此,基本上,第一个函数将排序后的数组转换为平衡的二进制搜索树,第二个函数从给定节点返回树的高度。编译程序时,出现如下错误:
我试图打印出“ aNode”对象进行测试,但我惊讶地发现它最初指向一个Node对象,但是随后指向了一个Tree对象(?),我对此感到非常困惑,并且确实不知道。不知道该如何调试。非常感谢您的帮助。
class Node(object):
def __init__(self, data):
self.data = data
self.lChild = None
self.rChild = None
class Tree(object):
def __init__(self):
self.root = None
# create a balanced binary search tree from a sorted list
def create_tree (self, a_list):
if (len(a_list) <= 0): return None
mid = (len(a_list))//2 # find the mid value of the sorted array & make it root
self.root = Node(a_list[mid])
self.root.lChild = self.create_tree(a_list[:mid])
self.root.rChild = self.create_tree(a_list[mid+1:])
return self
def get_height (self, aNode):
if (aNode == None):
return -1
else:
print(aNode) # I DID MY TEST HERE WHERE IT FIRST PRINT "NODE OBJECT", BUT PRINT "TREE OBJECT" LATER AND CAUSE THE PROGRAM TO FAIL
rHeight = self.get_height(aNode.rChild)
lHeight = self.get_height(aNode.lChild)
return (1+rHeight) if rHeight > lHeight else (1+lHeight)
def main():
new_tree = Tree().create_tree([1,9,11,17])
new_tree.get_height(new_tree.root)
main()
非常感谢您!
答案 0 :(得分:1)
问题是您每次都用一个新节点覆盖self.root。因此,在递归调用中的每个级别下,您都将使用新的空节点重置Tree对象的self.root。
对代码进行一些较小的更改即可解决此问题。还向main的get_height()调用中添加了打印内容,因为它仅返回整数,并且您没有将其分配给任何内容。
class Node(object):
def __init__(self, data):
self.data = data
self.lChild = None
self.rChild = None
class Tree(object):
def __init__(self, a_list):
self.root = self.create_tree(a_list)
# create a balanced binary search tree from a sorted list
def create_tree (self, a_list):
if (len(a_list) <= 0): return None
mid = (len(a_list))//2
root = Node(a_list[mid])
root.lChild = self.create_tree(a_list[:mid])
root.rChild = self.create_tree(a_list[mid+1:])
return root
def get_height (self, aNode):
if (aNode == None):
return -1
else:
print(aNode)
rHeight = self.get_height(aNode.rChild)
lHeight = self.get_height(aNode.lChild)
return (1+rHeight) if rHeight > lHeight else (1+lHeight)
def main():
new_tree = Tree([1,9,11,17])
print(new_tree.get_height(new_tree.root))