我实现了一个deleted函数,它从二叉树中删除一个特定的节点。num\u child()返回一个节点的子节点数,get\u left()返回左子节点数,依此类推。它适用于我尝试过的所有情况。我想知道代码是否正确?有没有什么方法可以简化代码?
def _delete(self):
# if the node has 2 children
if self.num_child() == 2:
print("Cannot delete the node coz it has two child")
# if the node has 1 child
if self.num_child() == 1:
#if left child is present
if self.get_left() is not None:
child=self.left
#for root condition
if self.parent is None:
self.left.parent = None
self.left= None
else:
self.left.parent = self.parent
if self.data is self.parent.get_left():
self.parent.left = self.left
if self.data is self.parent.get_right():
self.parent.right = self.left
#if right child is present
if self.get_right() is not None:
#for root condition
if self.parent is None:
self.right.parent = None
self.right= None
else:
self.right.parent = self.parent
if self.data is self.parent.get_left():
self.parent.left = self.right
if self.data is self.parent.get_right():
self.parent.right = self.right
print(f"{self.data} has been deleted")
return
if self.num_child() == 0:
if self.data is self.parent.get_left():
self.parent.left = None
self.parent= None
elif self.data is self.parent.get_right():
self.parent.right = None
self.parent= None
print(f"{self.data} has been deleted")
暂无答案!
目前还没有任何答案,快来回答吧!