Merge pull request #155 from brenobaptista/solution-617

Added solution 617
This commit is contained in:
halfrost
2021-06-27 08:13:45 +08:00
committed by GitHub
3 changed files with 126 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package leetcode
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
root1.Val += root2.Val
root1.Left = mergeTrees(root1.Left, root2.Left)
root1.Right = mergeTrees(root1.Right, root2.Right)
return root1
}

View File

@ -0,0 +1,63 @@
package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question617 struct {
para617
ans617
}
// para 是参数
// one 代表第一个参数
type para617 struct {
one []int
another []int
}
// ans 是答案
// one 代表第一个答案
type ans617 struct {
one []int
}
func Test_Problem617(t *testing.T) {
qs := []question617{
{
para617{[]int{}, []int{}},
ans617{[]int{}},
},
{
para617{[]int{}, []int{1}},
ans617{[]int{1}},
},
{
para617{[]int{1, 3, 2, 5}, []int{2, 1, 3, structures.NULL, 4, structures.NULL, 7}},
ans617{[]int{3, 4, 5, 5, 4, structures.NULL, 7}},
},
{
para617{[]int{1}, []int{1, 2}},
ans617{[]int{2, 2}},
},
}
fmt.Printf("------------------------Leetcode Problem 617------------------------\n")
for _, q := range qs {
_, p := q.ans617, q.para617
fmt.Printf("【input】:%v ", p)
root1 := structures.Ints2TreeNode(p.one)
root2 := structures.Ints2TreeNode(p.another)
fmt.Printf("【output】:%v \n", mergeTrees(root1, root2))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,30 @@
# [617. Merge Two Binary Trees](https://leetcode.com/problems/merge-two-binary-trees/)
## 题目
You are given two binary trees **root1** and **root2**.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return the merged tree.
**Note**: The merging process must start from the root nodes of both trees.
**Example 1**:
```
Input: root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
Output: [3,4,5,5,4,null,7]
```
**Example 2**:
```
Input: root1 = [1], root2 = [1,2]
Output: [2,2]
```
**Constraints**:
1. The number of nodes in both trees is in the range [0, 2000].
2. -104 <= Node.val <= 104