From f6db9d06e23986ea946d5108e2a921d261f1ef91 Mon Sep 17 00:00:00 2001 From: roylx <73628821+roylx@users.noreply.github.com> Date: Wed, 12 Oct 2022 10:34:56 -0600 Subject: [PATCH] =?UTF-8?q?Update=200701.=E4=BA=8C=E5=8F=89=E6=90=9C?= =?UTF-8?q?=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D?= =?UTF-8?q?=E4=BD=9C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0701.二叉搜索树中的插入操作.md Python3 **递归法** - 无返回值 有注释 不用Helper function --- .../0701.二叉搜索树中的插入操作.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 599dd073..6a78b2b4 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -330,6 +330,27 @@ class Solution: return root ``` +**递归法** - 无返回值 有注释 不用Helper function +``` +class Solution: + last = None + 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