Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 45a01ee

Browse files
committed
添加 0701.二叉搜索树中的插入操作.md Scala版本
1 parent f6456c3 commit 45a01ee

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎problems/0701.二叉搜索树中的插入操作.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -585,6 +585,43 @@ function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
585585
```
586586

587587

588+
## Scala
589+
590+
递归:
591+
592+
```scala
593+
object Solution {
594+
def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = {
595+
if (root == null) return new TreeNode(`val`)
596+
if (`val` < root.value) root.left = insertIntoBST(root.left, `val`)
597+
else root.right = insertIntoBST(root.right, `val`)
598+
root // 返回根节点
599+
}
600+
}
601+
```
602+
603+
迭代:
604+
605+
```scala
606+
object Solution {
607+
def insertIntoBST(root: TreeNode, `val`: Int): TreeNode = {
608+
if (root == null) {
609+
return new TreeNode(`val`)
610+
}
611+
var parent = root // 记录当前节点的父节点
612+
var curNode = root
613+
while (curNode != null) {
614+
parent = curNode
615+
if(`val` < curNode.value) curNode = curNode.left
616+
else curNode = curNode.right
617+
}
618+
if(`val` < parent.value) parent.left = new TreeNode(`val`)
619+
else parent.right = new TreeNode(`val`)
620+
root // 最终返回根节点
621+
}
622+
}
623+
```
624+
588625

589626
-----------------------
590627
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /