我正在尝试解决这个问题。这个问题基本上是创建一个可以从 BST 中删除节点的函数。
看到解决方案后,我尝试自己编写解决方案。 这是我的尝试
def getSuccessor(node):
node = node.right
while node and node.left:
node = node.left
return node.data
#Function to delete a node from BST.
def deleteNode(root, X):
# code here.
if root is None:
return root
elif root.data>X:
root.left = deleteNode(root.left,X)
elif root.data<X:
root.right = deleteNode(root.right,X)
else:
if root.left is None:
return root.right
elif root.right is None:
return root.left
else:
root.data = getSuccessor(root)
# print(root.data)
root.right = deleteNode(root.right,root.data)
return root
解决方案在这里
#User function Template for python3
def getSuccessor(node):
node = node.right
while node and node.left:
node = node.left
return node
def deleteNode(root, X):
if root is None:
return root
elif root.data > X:
root.left = deleteNode(root.left, X)
elif root.data < X:
root.right = deleteNode(root.right, X)
else:
if root.left is None:
return root.right
elif root.right is None:
return root.left
else:
temp = getSuccessor(root)
root.data = temp.data
root.right = deleteNode(root.right, temp.data)
return root
我只更改了上面的 getSuccessor 函数,因为我只需要 node.data 但它不起作用,我认为这与 python 通过引用传递对象有关,但无法理解如何?
我尝试更改解决方案,但代码未按预期工作。
我只改变了上面的
功能getSuccessor
还有更多差异。您已经移动了最后一个
return root
,因此现在有些情况下您的函数不执行 return
语句,而是返回 None
。
这应该很容易发现。解决方法是将
return root
语句准确放置在工作版本中的位置,即具有相同的缩进。