mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
添加 0654.最大二叉树.md Scala版本
This commit is contained in:
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
-----------------------
|
||||
<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