|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
class BTree(object):
def __init__(self, data=None, left=None, right=None): #定义二叉树
self.data = data
self.left = left
self.right = right
def height(self): #求二叉树高度
if self.data is None:
return 0
elif self.data is None and self.right is None:
return 1
elif self.left is None and self.right is not None:
return 1 + self.right.height()
elif self.left is not None and self.right is None:
return 1 + self.left.height()
else:
return 1 + max(self.left.height(), self.right.height())
right_tree = BTree(6) #建立二叉树
right_tree.left = BTree(2)
right_tree.right = BTree(4)
left_tree = BTree(5)
left_tree.left = BTree(1)
left_tree.right = BTree(3)
tree = BTree(11)
tree.left = left_tree
tree.right = right_tree
tree.height()
运行后报错如下:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-33-85a0577fd879> in <module>
28 tree.right = right_tree
29
---> 30 tree.height()
<ipython-input-33-85a0577fd879> in height(self)
14 return 1 + self.left.height()
15 else:
---> 16 return 1 + max(self.left.height(), self.right.height())
17
18 right_tree = BTree(6)
<ipython-input-33-85a0577fd879> in height(self)
14 return 1 + self.left.height()
15 else:
---> 16 return 1 + max(self.left.height(), self.right.height())
17
18 right_tree = BTree(6)
<ipython-input-33-85a0577fd879> in height(self)
14 return 1 + self.left.height()
15 else:
---> 16 return 1 + max(self.left.height(), self.right.height())
17
18 right_tree = BTree(6)
AttributeError: 'NoneType' object has no attribute 'height'
我想着是方法名字的问题吗还是什么,跟着视频敲的代码,不知道为什么运行不了 |
|