Delete Node in a BST
就是BST的删除操作,但是也是BST里面最复杂的一个基本操作了,首先要找到删除点,然后判断此点有无子树,如果没有左子树,则把右子树换上来,如果没有右子树,则把左子树换上来,如果都有,则需要用findMin函数找到当前点的后继点,然后把后继点换到当前位置,下面是代码
class Solution(object):
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root:
return None
if root.val < key:
root.right = self.deleteNode(root.right, key)
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
if not root.left:
tmp = root.right
root = None
return tmp
elif not root.right:
tmp = root.left
root = None
return tmp
tmp = self.findMin(root.right)
root.val = tmp.val
root.right = self.deleteNode(root.right, root.val)
return root
def findMin(self, root):
while root.left:
root = root.left
return root