From 279daa736f248cc260531be269c93d1165be4507 Mon Sep 17 00:00:00 2001 From: LehiChiang Date: Thu, 13 May 2021 19:38:47 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0701.=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=20Java/Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0701.二叉搜索树中的插入操作.md | 39 +++++++++++++++++-- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 760509d9..26c6bb9c 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -16,7 +16,7 @@ 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。 ![701.二叉搜索树中的插入操作](https://img-blog.csdnimg.cn/20201019173259554.png) -  + 提示: * 给定的树上的节点数介于 0 和 10^4 之间 @@ -206,12 +206,45 @@ public: ## 其他语言版本 - Java: +递归法 + +```java +class Solution { + public TreeNode insertIntoBST(TreeNode root, int val) { + return buildTree(root, val); + } + + public TreeNode buildTree(TreeNode root, int val){ + if (root == null) // 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。 + return new TreeNode(val); + if (root.val < val){ + root.right = buildTree(root.right, val); // 递归创建右子树 + }else if (root.val > val){ + root.left = buildTree(root.left, val); // 递归创建左子树 + } + return root; + } +} +``` Python: +递归法 + +```python +class Solution: + def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: + if root is None: + return TreeNode(val) # 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。 + if root.val < val: + root.right = self.insertIntoBST(root.right, val) # 递归创建右子树 + if root.val > val: + root.left = self.insertIntoBST(root.left, val) # 递归创建左子树 + return root +``` + Go: @@ -222,4 +255,4 @@ Go: * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
+
\ No newline at end of file