diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 50e39ade..135911b9 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -585,6 +585,43 @@ function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { ``` +## Scala + +递归: + +```scala +object Solution { + def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = { + if (root == null) return new TreeNode(`val`) + if (`val` < root.value) root.left = insertIntoBST(root.left, `val`) + else root.right = insertIntoBST(root.right, `val`) + root // 返回根节点 + } +} +``` + +迭代: + +```scala +object Solution { + def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = { + if (root == null) { + return new TreeNode(`val`) + } + var parent = root // 记录当前节点的父节点 + var curNode = root + while (curNode != null) { + parent = curNode + if(`val` < curNode.value) curNode = curNode.left + else curNode = curNode.right + } + if(`val` < parent.value) parent.left = new TreeNode(`val`) + else parent.right = new TreeNode(`val`) + root // 最终返回根节点 + } +} +``` + -----------------------