如何解决二进制搜索树删除方法不起作用
这是我尝试实现的BST,但是remove方法不会删除具有给定值的节点。 我尝试过这种方式:
- 首先检查当前节点(我要删除的节点)是否有合适的孩子。
1.1)如果没有,那么我将当前节点替换为其左子节点。
1.2)并且如果当前节点有一个右孩子,则检查当前节点的右孩子是否有一个左孩子
1.2.1)如果右子节点有左子节点,则将当前节点替换为大于当前节点的最小节点,并替换为右子树中的最左侧节点
1.2.2)如果没有,则用其正确的子代替换当前节点。 但是该代码不会删除所选节点。我在哪里弄错了?
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,value):
node = {'value':value,'left':None,'right':None}
if self.root == None:
self.root = node
else:
current = self.root
while True:
if value > current['value']:
if current['right'] == None:
current['right'] = node
break
else:
current = current['right']
else:
if current['left'] == None:
current['left'] = node
break
else:
current = current['left']
def lookup(self,value):
if self.root == None:
return
else:
current = self.root
while True:
if value > current['value']:
if current['right'] == None:
return None
current = current['right']
elif value < current['value']:
if current['left'] == None:
return None
current = current['left']
else:
return current
def remove(self,value):
if not self.root:
return False
parent = None
current = self.root
while current:
if value < current['value']:
parent = current
current = current['left']
elif value > current['value']:
parent = current
current = current['right']
elif value == current['value']:
# 1)no right child
if current['right'] == None:
if parent == None:
self.root = current['left']
else:
if current['value'] < parent['value']:
parent['left'] = current['left']
elif current['value'] > parent['value']:
parent['right'] = current['left']
# 2) right child that doesnt have a left child
elif current['right']['left'] == None:
current['right']['left'] = current['left']
if parent == None:
self.root= current['right']
else:
if parent['value'] > current['value']:
parent['left'] = current['right']
elif parent['value'] < current['value']:
parent['right'] = current['right']
# 3)Right child that has a left child
else:
#finding the right child's leftmost child
leftmost = current['right']['left']
leftmostParent = current['right']
while leftmost['left'] != None:
leftmostParent = leftmost
leftmost = leftmost['left']
leftmostParent['left'] = leftmost['right']
leftmost['left'] = current['left']
leftmost['right'] = current['right']
if parent == None:
self.root = leftmost
else:
if current['value'] < parent['value']:
parent['left'] = leftmost
elif current['value'] > parent['value']:
parent['right'] = leftmost
return True
def get(self):
my_bst = {
'root':self.root,}
return my_bst
bst = BinarySearchTree()
bst.insert(9)
bst.insert(4)
bst.insert(6)
bst.insert(20)
bst.insert(170)
bst.insert(15)
bst.insert(1)
bst.insert(150)
print(bst.remove(150))
print(bst.get())
解决方法
您的while current:
循环实际上永远不会循环,因为您return True
在循环结束时。我认为向右缩进return True
可以解决问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。