mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加 0701.二叉搜索树中的插入操作.md Scala版本
This commit is contained in:
@ -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>
|
||||
|
Reference in New Issue
Block a user