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

0450.删除二叉搜索树中的节点.md 添加python3迭代法
This commit is contained in:
roylx
2022-10-12 14:07:50 -06:00
committed by GitHub
parent abb348dbc4
commit bd77b3bb63

View File

@ -344,6 +344,48 @@ class Solution:
return root
```
**迭代法**
```python
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
# 找到节点后分两步1. 把节点的左子树和右子树连起来2. 把右子树跟父节点连起来
# root is None
if not root: return root
p = root
last = None
while p:
if p.val==key:
# 1. connect left to right
# right is not None -> left is None | left is not None
if p.right:
if p.left:
node = p.right
while node.left:
node = node.left
node.left = p.left
right = p.right
else:
# right is None -> right=left
right = p.left
# 2. connect right to last
if last==None:
root = right
elif last.val>key:
last.left = right
else:
last.right = right
# 3. return
break
else:
# Update last and continue
last = p
if p.val>key:
p = p.left
else:
p = p.right
return root
```
## Go
```Go
// 递归版本