mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-11 04:54:51 +08:00
添加 0700.二叉搜索树中的搜索.md Scala版本
This commit is contained in:
@ -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>
|
<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