添加 0617.合并二叉树.md Scala版本

This commit is contained in:
ZongqinWang
2022-05-27 16:37:53 +08:00
parent 821ca656e1
commit de34170f5c

View File

@ -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 // 返回nodereturn关键字可以省略
}
}
```
迭代:
```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
}
}
```
-----------------------