mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1511 from Miraclelucy/master
Update 0450.删除二叉搜索树中的节点.md
This commit is contained in:
@ -322,33 +322,25 @@ class Solution {
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
|
||||
if not root: return root #第一种情况:没找到删除的节点,遍历到空节点直接返回了
|
||||
if root.val == key:
|
||||
if not root.left and not root.right: #第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
|
||||
del root
|
||||
return None
|
||||
if not root.left and root.right: #第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
|
||||
tmp = root
|
||||
root = root.right
|
||||
del tmp
|
||||
return root
|
||||
if root.left and not root.right: #第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
|
||||
tmp = root
|
||||
root = root.left
|
||||
del tmp
|
||||
return root
|
||||
else: #第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
|
||||
v = root.right
|
||||
while v.left:
|
||||
v = v.left
|
||||
v.left = root.left
|
||||
tmp = root
|
||||
root = root.right
|
||||
del tmp
|
||||
return root
|
||||
if root.val > key: root.left = self.deleteNode(root.left,key) #左递归
|
||||
if root.val < key: root.right = self.deleteNode(root.right,key) #右递归
|
||||
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[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 : return root.right
|
||||
# 当前节点的右子树为空,返回当前的左子树
|
||||
if not root.right: return root.left
|
||||
# 左右子树都不为空,找到右孩子的最左节点 记为p
|
||||
node = root.right
|
||||
while node.left :
|
||||
node = node.left
|
||||
# 将当前节点的左子树挂在p的左孩子上
|
||||
node.left = root.left
|
||||
# 当前节点的右子树替换掉当前节点,完成当前节点的删除
|
||||
root = root.right
|
||||
return root
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user