Skip to content

Commit 4184805

Browse files
committed
Add Solution.java for 0617.Merge Two Binary Trees
1 parent df0a013 commit 4184805

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Merge Two Binary Trees
2+
3+
Given two binary trees and 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.
4+
5+
You need to merge them 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 new tree.
6+
7+
## Example 1:
8+
```
9+
Input:
10+
Tree 1 Tree 2
11+
1 2
12+
/ \ / \
13+
3 2 1 3
14+
/ \ \
15+
5 4 7
16+
Output:
17+
Merged tree:
18+
3
19+
/ \
20+
4 5
21+
/ \ \
22+
5 4 7
23+
```
24+
25+
##Note:
26+
The merging process must start from the root nodes of both trees.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
12+
if (t1 == null) return t2;
13+
if (t2 == null) return t1;
14+
15+
t1.val = t1.val + t2.val;
16+
t1.left = mergeTrees(t1.left, t2.left);
17+
t1.right = mergeTrees(t1.right, t2.right);
18+
return t1;
19+
}
20+
}

0 commit comments

Comments
 (0)