Skip to content

Commit 5bf5416

Browse files
authored
Update 0450.删除二叉搜索树中的节点.md 添加普通二叉树的删除方式python3代码
1 parent 25020c6 commit 5bf5416

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

problems/0450.删除二叉搜索树中的节点.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -348,6 +348,24 @@ class Solution:
348348
return root
349349
```
350350

351+
**普通二叉树的删除方式**
352+
```python
353+
class Solution:
354+
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
355+
if not root: return root
356+
if root.val == key:
357+
if not root.right: # 这里第二次操作目标值:最终删除的作用
358+
return root.left
359+
tmp = root.right
360+
while tmp.left:
361+
tmp = tmp.left
362+
root.val, tmp.val = tmp.val, root.val # 这里第一次操作目标值:交换目标值其右子树最左面节点。
363+
364+
root.left = self.deleteNode(root.left, key)
365+
root.right = self.deleteNode(root.right, key)
366+
return root
367+
```
368+
351369
**迭代法**
352370
```python
353371
class Solution:

0 commit comments

Comments
 (0)