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 @@ 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。  - + 提示: * 给定的树上的节点数介于 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) -