mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Update 0450.删除二叉搜索树中的节点.md
0450.删除二叉搜索树中的节点.md 添加python3迭代法
This commit is contained in:
@ -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
|
||||
// 递归版本
|
||||
|
Reference in New Issue
Block a user