添加 0700.二叉搜索树中的搜索.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-27 17:01:56 +08:00
parent 0e3a1bc3dc
commit 9412e2e405

View File

@ -363,7 +363,34 @@ function searchBST(root: TreeNode | null, val: number): TreeNode | null {
};
```
## Scala
递归:
```scala
object Solution {
def searchBST(root: TreeNode, value: Int): TreeNode = {
if (root == null || value == root.value) return root
// 相当于三元表达式在Scala中if...else有返回值
if (value < root.value) searchBST(root.left, value) else searchBST(root.right, value)
}
}
```
迭代:
```scala
object Solution {
def searchBST(root: TreeNode, value: Int): TreeNode = {
// 因为root是不可变量所以需要赋值给一个可变量
var node = root
while (node != null) {
if (value < node.value) node = node.left
else if (value > node.value) node = node.right
else return node
}
null // 没有返回就返回空
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>