-
Notifications
You must be signed in to change notification settings - Fork 23
/
Merge Two Binary Trees.java
executable file
·95 lines (85 loc) · 2.78 KB
/
Merge Two Binary Trees.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
E
1525670223
tags: DFS, Tree
#### DFS
- 基础binary tree traversal. 注意对null child的判断
```
/*
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.
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.
Example 1:
Input:
Tree 1 Tree 2
1 2
/ \ / \
3 2 1 3
/ \ \
5 4 7
Output:
Merged tree:
3
/ \
4 5
/ \ \
5 4 7
Note: The merging process must start from the root nodes of both trees.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// Same idea, differnet way to write
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) {
return null;
}
TreeNode node = new TreeNode(0);
node.val += t1 == null ? 0 : t1.val;
node.val += t2 == null ? 0 : t2.val;
TreeNode t1LeftChild = t1 == null ? null : t1.left;
TreeNode t2LeftChild = t2 == null ? null : t2.left;
TreeNode t1RightChild = t1 == null ? null : t1.right;
TreeNode t2RightChild = t2 == null ? null : t2.right;
node.left = mergeTrees(t1LeftChild, t2LeftChild);
node.right = mergeTrees(t1RightChild, t2RightChild);
return node;
}
}
/*
Thoughts:
1. Regular traversal. Always pass t1, t2.
2. Chech closing conditions: thinking from the leaf's perspective where it stops the resersive calls
*/
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) {
return null;
}
final TreeNode node = new TreeNode(0);
if (t2 == null) {
node.val += t1.val;
node.left = mergeTrees(t1.left, null);
node.right = mergeTrees(t1.right, null);
} else if (t1 == null) {
node.val += t2.val;
node.left = mergeTrees(null, t2.left);
node.right = mergeTrees(null, t2.right);
} else {
node.val = t1.val + t2.val;
node.left = mergeTrees(t1.left, t2.left);
node.right = mergeTrees(t1.right, t2.right);
}
return node;
}
}
```