[英]How do I modify my current binary search tree to be able to create an empty tree?
so far my code for creating a binary search tree is fine for what I'm trying to accomplish.到目前为止,我用于创建二叉搜索树的代码对于我想要完成的工作来说很好。 However I would like for the
new
function to create an empty tree but my whole code as far as I can understand is based on a root value called when instancing a new object.但是,我希望
new
函数创建一棵空树,但据我所知,我的整个代码基于实例化新对象时调用的根值。 How would I go about changing the code for new
to return an empty BST instead of a tree with one root value as base?我将如何更改
new
的代码以返回一个空的 BST 而不是以一个根值作为基数的树? A relevant issue is also that the size
attribute needs to start at 1 and I would like for it to start at 0. Thank you in advance.一个相关的问题是
size
属性需要从 1 开始,我希望它从 0 开始。在此先感谢您。
Below is all the code linked.下面是所有链接的代码。
class BinaryTree:
def __init__(self, root):
self._root = root
self._left = None
self._right = None
self._size = 1
def add(self, root):
if self._root:
if root < self._root:
if self._left is None:
self._left = BinaryTree(root)
self._size += 1
else:
self._left.add(root)
self._size += 1
elif root > self._root:
if self._right is None:
self._right = BinaryTree(root)
self._size += 1
else:
self._right.add(root)
self._size += 1
else:
self._root = root
def string(self):
if self._left:
self._left.string()
print(self._root),
if self._right:
self._right.string()
def len(self):
return self._size
def new(root):
return BinaryTree(root)
I've mark added/changed lines with # changed
comment:我用
# changed
注释标记了添加/更改的行:
class BinaryTree:
def __init__(self, root=None): # changed
self._root = root
self._left = None
self._right = None
self._size = 1 if root is not None else 0 # changed
def add(self, root):
if self._root:
if root < self._root:
if self._left is None:
self._left = BinaryTree(root)
self._size += 1
else:
self._left.add(root)
self._size += 1
elif root > self._root:
if self._right is None:
self._right = BinaryTree(root)
self._size += 1
else:
self._right.add(root)
self._size += 1
else:
self._root = root
self._size = 1 # changed
def string(self):
if self._left:
self._left.string()
print(self._root) # changed, removed ","
if self._right:
self._right.string()
def len(self):
return self._size
def new(root=None):
return BinaryTree(root)
Check also magic methods __str__
and __len__
they could help.还检查魔术方法
__str__
和__len__
他们可以提供帮助。 Method add
migth returns self
which allow to add elements one by one in chain like that add(1).add(10).add(100)
.方法
add
migth 返回self
,它允许像add(1).add(10).add(100)
那样在链中一个一个地添加元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.