Skip to content

Commit

Permalink
添加 0654.最大二叉树.md Scala版本
Browse files Browse the repository at this point in the history
  • Loading branch information
wzqwtt committed May 27, 2022
1 parent 0e3a1bc commit 821ca65
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions problems/0654.最大二叉树.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>

0 comments on commit 821ca65

Please sign in to comment.