diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index c56a2624..25d39486 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -283,32 +283,10 @@ class Solution: return TreeNode(val) self.traversal(root, val) return root - ``` 递归法(版本二) ```python -class Solution: - def insertIntoBST(self, root, val): - if root is None: - return TreeNode(val) - parent = None - cur = root - while cur: - parent = cur - if val < cur.val: - cur = cur.left - else: - cur = cur.right - if val < parent.val: - parent.left = TreeNode(val) - else: - parent.right = TreeNode(val) - return root -``` - -递归法(版本三) -```python class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None or root.val == val: @@ -326,7 +304,7 @@ class Solution: return root ``` -递归法(版本四) +递归法(版本三) ```python class Solution: def insertIntoBST(self, root, val): @@ -340,10 +318,9 @@ class Solution: root.right = self.insertIntoBST(root.right, val) return root - ``` -迭代法 +迭代法(版本一) ```python class Solution: def insertIntoBST(self, root, val): @@ -366,9 +343,28 @@ class Solution: else: parent.right = node # 将新节点连接到父节点的右子树 - return root + return root +``` - +迭代法(版本二) +```python +class Solution: + def insertIntoBST(self, root, val): + if root is None: + return TreeNode(val) + parent = None + cur = root + while cur: + parent = cur + if val < cur.val: + cur = cur.left + else: + cur = cur.right + if val < parent.val: + parent.left = TreeNode(val) + else: + parent.right = TreeNode(val) + return root ``` 迭代法(精简)