python输入后不能删除_在python中使用del语句后无法删除对象

1586010002-jmsa.png

class BinaryNode:

def __init__(self, value):

self.data = value

self.left = None

self.right = None

def contains(root, value):

if root is None:

return False

if value == root.data:

return True

if value < root.data:

return contains(root.left, value)

else:

return contains(root.right, value)

def insert(root, value):

if root is None:

root = BinaryNode(value)

else:

if value > root.data:

if root.right is None:

root.right = BinaryNode(value)

else:

return insert(root.right, value)

else:

if root.left is None:

root.left = BinaryNode(value)

else:

return insert(root.left, value)

def getMin(root):

if root.left is None:

return root

return getMin(root.left)

def remove(root, value):

if root is None:

return False

elif value < root.data:

remove(root.left, value)

elif value > root.data:

remove(root.right, value)

else:

if root.left is None and root.right is None:

del root

def inorder(root):

if root is not None:

inorder(root.left)

print(root.data)

inorder(root.right)

b = BinaryNode(10)

insert(b, 9)

insert(b, 11)

insert(b,8)

insert(b,9.5)

remove(b, 9.5)

inorder(b)

i'm constructing the functions of a binary search tree. So far, in writing my remove function I handle the case in which the root to be removed from the tree is a left node (node without any children). For this, all I would have to do say del root. This has no effect at all on the tree and the value 9.5 still exists.

解决方案

del only removes the reference, here the local name root. It won't delete the b reference you have at the top. You can't do what you want with a function; a function doesn't own the references in the caller.

At most you can wrap your root value in a separate BinaryTree class instance, than can be 'empty'. Give it a root attribute and if that attribute is set to None the tree is cleared.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值