450. 删除二叉搜索树中的节点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
# 基线条件
if root==None: return None # 没有找到要删除的点。
if root.val==key: # 有找到要删除的点。
if root.left==None and root.right==None: # 在叶子结点
return None
elif root.left==None and root.right:
return root.right
elif root.left and root.right==None:
return root.left
else: # 左右儿子都不空
cur = root.left
while cur.right: # 把右儿子拼接到左儿子的最大节点右侧。
cur = cur.right
cur.right = root.right
return root.left # 删除
# 递归遍历 重建bst结构
if root.val > key:
root.left = self.deleteNode(root.left,key)
elif root.val < key:
root.right = self.deleteNode(root.right,key)
return root