-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge.java
44 lines (43 loc) · 1.14 KB
/
Merge.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Merge {
public TreeNode mergeTrees1(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
t1.val += t2.val;
return t1;
}
public TreeNode mergeTrees2(TreeNode t1, TreeNode t2) {
if (t1 == null) return t2;
if (t2 == null) return t1;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(t1);
queue.offer(t2);
while (!queue.isEmpty()) {
TreeNode a = queue.poll();
TreeNode b = queue.poll();
a.val += b.val;
if (a.left == null) {
a.left = b.left;
} else {
if (b.left != null) {
queue.offer(a.left);
queue.offer(b.left);
}
}
if (a.right == null) {
a.right = b.right;
} else {
if (b.right != null) {
queue.offer(a.right);
queue.offer(b.right);
}
}
}
return t1;
}
}