diff --git a/problems/0450.删除二叉搜索树中的节点.md b/problems/0450.删除二叉搜索树中的节点.md index 4ae092a2..d178596e 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 // 递归版本 diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 039c3b6d..2e899e22 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -330,6 +330,26 @@ class Solution: return root ``` +**递归法** - 无返回值 有注释 不用Helper function +```python +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: # for root==None + return TreeNode(val) + if root.valval: + if root.left==None: # found the parent + root.left = TreeNode(val) + else: # not found, keep searching + self.insertIntoBST(root.left, val) + # return the final tree + return root +``` + **迭代法** 与无返回值的递归函数的思路大体一致 ```python @@ -337,16 +357,15 @@ class Solution: def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: if not root: return TreeNode(val) - parent = None + parent = None # 此步可以省略 cur = root # 用while循环不断地找新节点的parent while cur: + parent = cur # 首先保存当前非空节点作为下一次迭代的父节点 if cur.val < val: - parent = cur cur = cur.right elif cur.val > val: - parent = cur cur = cur.left # 运行到这意味着已经跳出上面的while循环,