Merge pull request #1418 from wzqwtt/tree16

添加(0701.二叉搜索树中的插入操作、0450.删除二叉搜索树中的节点) Scala版本
This commit is contained in:
程序员Carl
2022-07-04 09:06:45 +08:00
committed by GitHub
2 changed files with 65 additions and 0 deletions

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>