@@ -585,6 +585,43 @@ function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null {
585
585
```
586
586
587
587
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
+
588
625
589
626
-----------------------
590
627
<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
0 commit comments