From 821ca656e14384fd63e937a0cd99fbe7bde813f0 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Fri, 27 May 2022 16:10:35 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200654.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0654.最大二叉树.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0654.最大二叉树.md b/problems/0654.最大二叉树.md index 1c73354b..1b0eac66 100644 --- a/problems/0654.最大二叉树.md +++ b/problems/0654.最大二叉树.md @@ -476,7 +476,33 @@ func traversal(_ nums: inout [Int], _ left: Int, _ right: Int) -> TreeNode? { } ``` +## Scala +```scala +object Solution { + def constructMaximumBinaryTree(nums: Array[Int]): TreeNode = { + if (nums.size == 0) return null + // 找到数组最大值 + var maxIndex = 0 + var maxValue = Int.MinValue + for (i <- nums.indices) { + if (nums(i) > maxValue) { + maxIndex = i + maxValue = nums(i) + } + } + + // 构建一棵树 + var root = new TreeNode(maxValue, null, null) + + // 递归寻找左右子树 + root.left = constructMaximumBinaryTree(nums.slice(0, maxIndex)) + root.right = constructMaximumBinaryTree(nums.slice(maxIndex + 1, nums.length)) + + root // 返回root + } +} +``` -----------------------