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 + } +} +``` -----------------------