Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de34170

Browse files
committed
添加 0617.合并二叉树.md Scala版本
1 parent 821ca65 commit de34170

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎problems/0617.合并二叉树.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,60 @@ function mergeTrees(root1: TreeNode | null, root2: TreeNode | null): TreeNode |
631631
};
632632
```
633633

634+
## Scala
635+
636+
递归:
637+
```scala
638+
object Solution {
639+
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
640+
if (root1 == null) return root2 // 如果root1为空,返回root2
641+
if (root2 == null) return root1 // 如果root2为空,返回root1
642+
// 新建一个节点,值为两个节点的和
643+
var node = new TreeNode(root1.value + root2.value)
644+
// 往下递归
645+
node.left = mergeTrees(root1.left, root2.left)
646+
node.right = mergeTrees(root1.right, root2.right)
647+
node // 返回node,return关键字可以省略
648+
}
649+
}
650+
```
634651

652+
迭代:
653+
```scala
654+
object Solution {
655+
import scala.collection.mutable
656+
def mergeTrees(root1: TreeNode, root2: TreeNode): TreeNode = {
657+
if (root1 == null) return root2
658+
if (root2 == null) return root1
659+
var stack = mutable.Stack[TreeNode]()
660+
// 先放node2再放node1
661+
stack.push(root2)
662+
stack.push(root1)
663+
while (!stack.isEmpty) {
664+
var node1 = stack.pop()
665+
var node2 = stack.pop()
666+
node1.value += node2.value
667+
if (node1.right != null && node2.right != null) {
668+
stack.push(node2.right)
669+
stack.push(node1.right)
670+
} else {
671+
if(node1.right == null){
672+
node1.right = node2.right
673+
}
674+
}
675+
if (node1.left != null && node2.left != null) {
676+
stack.push(node2.left)
677+
stack.push(node1.left)
678+
} else {
679+
if(node1.left == null){
680+
node1.left = node2.left
681+
}
682+
}
683+
}
684+
root1
685+
}
686+
}
687+
```
635688

636689

637690
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /