Merge pull request #1420 from wzqwtt/tree17

添加(0669.修剪二叉搜索树、0108.将有序数组转换为二叉搜索树) Scala版本
This commit is contained in:
程序员Carl
2022-07-05 09:49:05 +08:00
committed by GitHub
2 changed files with 36 additions and 0 deletions

View File

@ -448,5 +448,27 @@ struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
}
```
## Scala
递归:
```scala
object Solution {
def sortedArrayToBST(nums: Array[Int]): TreeNode = {
def buildTree(left: Int, right: Int): TreeNode = {
if (left > right) return null // 当left大于right的时候返回空
// 最中间的节点是当前节点
var mid = left + (right - left) / 2
var curNode = new TreeNode(nums(mid))
curNode.left = buildTree(left, mid - 1)
curNode.right = buildTree(mid + 1, right)
curNode
}
buildTree(0, nums.size - 1)
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

View File

@ -453,7 +453,21 @@ function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | n
};
```
## Scala
递归法:
```scala
object Solution {
def trimBST(root: TreeNode, low: Int, high: Int): TreeNode = {
if (root == null) return null
if (root.value < low) return trimBST(root.right, low, high)
if (root.value > high) return trimBST(root.left, low, high)
root.left = trimBST(root.left, low, high)
root.right = trimBST(root.right, low, high)
root
}
}
```
-----------------------