From 8dc91092774defa6ab621b1d50de1968df6cc7ba Mon Sep 17 00:00:00 2001 From: wangq635 <643797037@qq.com> Date: Sun, 1 Sep 2024 19:49:39 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B90701.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5?= =?UTF-8?q?=E6=93=8D=E4=BD=9C=EF=BC=8C=E5=A2=9E=E5=8A=A0python=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E7=9A=84=E8=BF=AD=E4=BB=A3=E6=B3=95=EF=BC=88=E7=B2=BE?= =?UTF-8?q?=E7=AE=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0701.二叉搜索树中的插入操作.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 6b9e5834..c56a2624 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -370,6 +370,30 @@ class Solution: ``` + +迭代法(精简) +```python +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if not root: # 如果根节点为空,创建新节点作为根节点并返回 + return TreeNode(val) + cur = root + while cur: + if val < cur.val: + if not cur.left: # 如果此时父节点的左子树为空 + cur.left = TreeNode(val) # 将新节点连接到父节点的左子树 + return root + else: + cur = cur.left + elif val > cur.val: + if not cur.right: # 如果此时父节点的左子树为空 + cur.right = TreeNode(val) # 将新节点连接到父节点的右子树 + return root + else: + cur = cur.right + +``` + ----- ### Go