mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
Update 0450.删除二叉搜索树中的节点.md 添加普通二叉树的删除方式python3代码
This commit is contained in:
@ -348,6 +348,24 @@ class Solution:
|
||||
return root
|
||||
```
|
||||
|
||||
**普通二叉树的删除方式**
|
||||
```python
|
||||
class Solution:
|
||||
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
|
||||
if not root: return root
|
||||
if root.val == key:
|
||||
if not root.right: # 这里第二次操作目标值:最终删除的作用
|
||||
return root.left
|
||||
tmp = root.right
|
||||
while tmp.left:
|
||||
tmp = tmp.left
|
||||
root.val, tmp.val = tmp.val, root.val # 这里第一次操作目标值:交换目标值其右子树最左面节点。
|
||||
|
||||
root.left = self.deleteNode(root.left, key)
|
||||
root.right = self.deleteNode(root.right, key)
|
||||
return root
|
||||
```
|
||||
|
||||
**迭代法**
|
||||
```python
|
||||
class Solution:
|
||||
|
Reference in New Issue
Block a user