添加 0701.二叉搜索树中的插入操作.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-29 13:04:37 +08:00
parent f6456c3b24
commit 45a01eed32

View File

@ -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 // 最终返回根节点
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>