我已經實現了二叉搜索樹的刪除功能。這個想法是聲明一個私有函數,它需要一個額外的參數來將self.root
抽象爲root
。在私人刪除功能中,它會進行條件檢查並確保root
等於需要刪除的數據。在條件檢查後,我編寫了3種不同的刪除情況。編譯代碼時沒有錯誤消息,也沒有刪除任何插入的節點。在python中的二叉搜索樹中實現刪除的麻煩
class Node(object):
def __init__(self, data, left=None, right=None, parent=None):
self.left = left
self.data = data
self.right = right
class Tree(object):
def __init__(self):
self.root = Node(None)
def delete(self,newData):
if self.root.data == None:
print 'The tree is empty'
else:
self.__delete(self.root, newData)
def __delete(self, root, newData):
# if newData smaller than root.data, change root to root.left, recursive call
if newData < root.data:
if root.left:
self.__delete(root.left, newData)
else:
return False
# if newData larger than root.data, change root to root.right, recursive call
elif newData > root.data:
if root.right:
self.__delete(root.right, newData)
else:
return False
elif newData == root.data:
#case 1, root has no child
if root.left is None and root.right is None:
root = None
#case 2, root has one child (left)
elif root.left is not None and root.right is None:
root.data = root.left.data
root.left = None
#case 3, root has one child (right)
elif root.right is not None and root.left is None:
root.data = root.right.data
root.right = None
#case 4, root has both children,
# find the smallest node in the right subtree, and swipe value
# delete smallest node in the right subtree
else:
root.data = self.__minValueToRightSubtree(root.right).data
self.__deleteMinValueToRightSubtree(root.right)
else:
print "Can't find this number"
def __minValueToRightSubtree(self, root):
if root.left is None:
return root
else:
return self.__minValueToRightSubtree(root.left)
def __deleteMinValueToRightSubtree(self, root):
if root.left is None:
root = None
return root
else:
self.__minValueToRightSubtree(root.left)
這段代碼錯了,您不期待什麼?我可以告訴你,情況2和3的根刪除是錯誤的,因爲當你試圖刪除根時,你保留'root.left'和'root.right'指針。 –
嘿。因此,我認爲在這些情況下,將數據從'root.left.data'或'root.right.data'複製到'root.data',並刪除左/右節點。這段代碼沒有收到任何錯誤消息,代碼也沒有做任何事情,所以我非常無知。你能否詳細說明爲什麼第2/3個案在閱讀我的過程之後出現錯誤 –
閱讀了這個...... elif root.right不是None並且root.left是None,然後閱讀這個'root.left = None' –