From bd77b3bb63445b8ab09d47a95ab7e4e07433b307 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 14:07:50 -0600 Subject: [PATCH] =?UTF-8?q?Update=200450.=E5=88=A0=E9=99=A4=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E8=8A=82?= =?UTF-8?q?=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0450.删除二叉搜索树中的节点.md 添加python3迭代法 --- .../0450.删除二叉搜索树中的节点.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 2d6d4ef2..541c8be4 100644 --- a/problems/0450.删除二叉搜索树中的节点.md +++ b/problems/0450.删除二叉搜索树中的节点.md @@ -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 // 递归版本