From 9412e2e40529db526bbb16de1f3a9c45cf2c3949 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 27 May 2022 17:01:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200700.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E4=B8=AD=E7=9A=84=E6=90=9C=E7=B4=A2?= =?UTF-8?q?.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0700.二叉搜索树中的搜索.md | 27 ++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/problems/0700.二叉搜索树中的搜索.md b/problems/0700.二叉搜索树中的搜索.md index 40cf4ea1..16ddef9b 100644 --- a/problems/0700.二叉搜索树中的搜索.md +++ b/problems/0700.二叉搜索树中的搜索.md @@ -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 // 没有返回就返回空 + } +} +``` -----------------------