我创建了一个二进制搜索类,但我正在努力创建一个最小函数来帮助找到二叉树中的最小值。
class BinarySearchTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert(self, new_data):
if new_data == self.data:
return
elif new_data < self.data:
if self.left == None:
self.left = BinarySearchTree(new_data)
else:
self.left.insert(new_data)
else:
if self.right == None:
self.right = BinarySearchTree(new_data)
else:
self.right.insert(new_data)
def create_string(self,spaces):
info = ' ' * spaces + str(self.data)
if self.left != None:
info += '\n(l)' + self.left.create_string(spaces + 4)
if not self.right == None:
info += '\n(r)' + self.right.create_string(spaces + 4)
return info
def __str__(self):
representation = self.create_string(0)
return representation
def get_left(self):
return self.left
def get_right(self):
return self.right
def get_data(self):
return self.data
def minimum(tree):
if tree.left:
return minimum(tree.get_left)
else:
return tree.get_left
所以我写了最小函数但由于某种原因它总是返回一个Nonetype错误。有没有人知道如何在二叉树上get_left,直到没有更多的节点
答案 0 :(得分:1)
非递归解决方案
def minimum(tree):
while tree.left is not None:
tree = tree.left
return tree.data
答案 1 :(得分:1)
如果没有tree.left
,您应该返回tree
:
def minimum(tree):
if tree.left:
return minimum(tree.get_left)
else:
return tree
正如您在问题中提到的,由于没有tree.left
返回tree.get_left
将返回None
答案 2 :(得分:1)
def minimum(tree):
if tree.left:
return minimum(tree.get_left)
else:
return tree
首先if语句检查tree.left = None,因此返回tree.get_left返回None。