From 95cc2b965807a6493fe64eb23d6bbfa66587f0fa Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 29 May 2022 10:18:40 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200236.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC=E5=85=B1?= =?UTF-8?q?=E7=A5=96=E5=85=88.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0236.二叉树的最近公共祖先.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/0236.二叉树的最近公共祖先.md b/problems/0236.二叉树的最近公共祖先.md index 69a6d0d6..a99180c3 100644 --- a/problems/0236.二叉树的最近公共祖先.md +++ b/problems/0236.二叉树的最近公共祖先.md @@ -343,7 +343,25 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree }; ``` +## Scala +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + // 递归结束条件 + if (root == null || root == p || root == q) { + return root + } + + var left = lowestCommonAncestor(root.left, p, q) + var right = lowestCommonAncestor(root.right, p, q) + + if (left != null && right != null) return root + if (left == null) return right + left + } +} +``` -----------------------
From 78930cdd0970c0850db6aa7c90ced0510fd6b1ec Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sun, 29 May 2022 10:32:47 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200235.=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88.md=20Scala=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...35.二叉搜索树的最近公共祖先.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index f7f1427a..a0f30999 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -381,7 +381,36 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree }; ``` +## Scala +递归: + +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + // scala中每个关键字都有其返回值,于是可以不写return + if (root.value > p.value && root.value > q.value) lowestCommonAncestor(root.left, p, q) + else if (root.value < p.value && root.value < q.value) lowestCommonAncestor(root.right, p, q) + else root + } +} +``` + +迭代: + +```scala +object Solution { + def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = { + var curNode = root // 因为root是不可变量,所以要赋值给curNode一个可变量 + while(curNode != null){ + if(curNode.value > p.value && curNode.value > q.value) curNode = curNode.left + else if(curNode.value < p.value && curNode.value < q.value) curNode = curNode.right + else return curNode + } + null + } +} +``` -----------------------