mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1411 from wzqwtt/tree12
添加(0654.最大二叉树、0617.合并二叉树) Scala版本
This commit is contained in:
@ -631,7 +631,60 @@ function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode |
|
||||
};
|
||||
```
|
||||
|
||||
## Scala
|
||||
|
||||
递归:
|
||||
```scala
|
||||
object Solution {
|
||||
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
|
||||
if (root1 == null) return root2 // 如果root1为空,返回root2
|
||||
if (root2 == null) return root1 // 如果root2为空,返回root1
|
||||
// 新建一个节点,值为两个节点的和
|
||||
var node = new TreeNode(root1.value + root2.value)
|
||||
// 往下递归
|
||||
node.left = mergeTrees(root1.left, root2.left)
|
||||
node.right = mergeTrees(root1.right, root2.right)
|
||||
node // 返回node,return关键字可以省略
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
迭代:
|
||||
```scala
|
||||
object Solution {
|
||||
import scala.collection.mutable
|
||||
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
|
||||
if (root1 == null) return root2
|
||||
if (root2 == null) return root1
|
||||
var stack = mutable.Stack[TreeNode]()
|
||||
// 先放node2再放node1
|
||||
stack.push(root2)
|
||||
stack.push(root1)
|
||||
while (!stack.isEmpty) {
|
||||
var node1 = stack.pop()
|
||||
var node2 = stack.pop()
|
||||
node1.value += node2.value
|
||||
if (node1.right != null && node2.right != null) {
|
||||
stack.push(node2.right)
|
||||
stack.push(node1.right)
|
||||
} else {
|
||||
if(node1.right == null){
|
||||
node1.right = node2.right
|
||||
}
|
||||
}
|
||||
if (node1.left != null && node2.left != null) {
|
||||
stack.push(node2.left)
|
||||
stack.push(node1.left)
|
||||
} else {
|
||||
if(node1.left == null){
|
||||
node1.left = node2.left
|
||||
}
|
||||
}
|
||||
}
|
||||
root1
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
@ -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