[英]Deleting a node from Binary Search tree
我试图从我的二进制搜索树中删除一个节点,我遵循了如何找到该节点并将其替换为子节点的一般格式,但是当我出于某种原因尝试删除一个没有子节点的节点并将父节点设置为NULL时当我尝试打印出节点时,它还没有删除数据?它是一个nonetype吗? 下面是我的测试用例(第二个尝试删除7时失败)我想如果我只是将节点设置为None,那还是可以的,但是由于某些原因我的列表仍然会打印7,即使那是应该的节点被删除
class T4_delete(unittest.TestCase):
def test_delete(self):
print("\n")
print("delete function")
t = lab3.Tree()
t.insert(8)
t.insert(3)
t.insert(10)
t.insert(1)
t.insert(6)
t.insert(4)
t.insert(7)
t.insert(14)
t.insert(13)
l1 = [node for node in t]
t.delete(7)
l2 = [node for node in t]
t.delete(6)
l3 = [node for node in t]
t.delete(8)
l4 = [node for node in t]
t.delete(10)
l5 = [node for node in t]
self.assertEqual(l1, [1, 3, 4, 6, 7, 8, 10, 13, 14])
self.assertEqual(l2, [1, 3, 4, 6, 8, 10, 13, 14])
self.assertEqual(l3, [1, 3, 4, 8, 10, 13, 14])
self.assertEqual(l4, [1, 3, 4, 10, 13, 14])
self.assertEqual(l5, [1, 3, 4, 13, 14])
print("\n")
这是我的删除函数,我使用辅助函数find节点找到了一个节点(哪个工作),然后我有if语句查看该节点是否有子节点,如果有两个节点,那么我将其替换为后继节点(如果有)拥有者,我用左孩子替换,如果没有,则尝试将节点设置为“无”。
def delete(self, data):
# Find the node to delete.
# If the value specified by delete does not exist in the tree, then don't change the tree and raise a KeyError
# If you find the node and ...
# a) The node has no children, just set it's parent's pointer to Null.
# b) The node has one child, make the nodes parent point to its child.
# c) The node has two children, replace it with its successor, and remove
# successor from its previous location.
# Recall: The successor of a node is the left-most node in the node's right subtree.
current = self.__find_node(data)
if current is None:
raise Keyerror
else:
if (current.left and current.right):
pre = self.find_successor(current.data)
current = pre
pre = None
elif (not current.left and not current.right):
print("Deleted data is", current.parent.data)
current = None
print("What happeneed",current)
else:
current = current.left
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.