[只有高度函数是我编写的,因此我对其余的代码没有任何控制。我不知道怎么了请帮助,在此先感谢
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, val):
if self.root == None:
self.root = Node(val)
else:
current = self.root
while True:
if val < current.info:
if current.left:
current = current.left
else:
current.left = Node(val)
break
elif val > current.info:
if current.right:
current = current.right
else:
current.right = Node(val)
break
else:
break
# Enter your code here. Read input from STDIN. Print output to STDOUT
'''
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
// this is a node of the tree , which contains info as data, left , right
'''
def height(root):
if root == None:
return 0
else:
leftheight= 1+height(root.left)
rightheight= 1+height(root.right)
if leftheight>rightheight:
return leftheight
else:
return rightheight
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.create(arr[i])
print(height(tree.root))
输出总是比实际高度小一,例如,如果树的高度为3,则返回4
尝试一下:
def height(root):
if root is None:
return 0
else:
return 1 + max(height(root.left), height(root.right))