-
Notifications
You must be signed in to change notification settings - Fork 26
/
617. Merge Two Binary Trees
103 lines (84 loc) · 2.87 KB
/
617. Merge Two Binary Trees
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
96
97
98
99
100
101
102
103
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
//If t1 == NULL -> t2
//If t2 == NULL -> t2
// Sum (t1,t2)
//Preorder Traversal (P -> L -> R)
if(t1 == null) return t2;
if(t2 == null) return t1;
t1.val+=t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
//If t1 == NULL -> t2
//If t2 == NULL -> t2
// Sum (t1,t2)
if(t1 == null) return t2;
if(t2 == null) return t1;
Stack<TreeNode[]> st = new Stack<>();
st.push(new TreeNode[]{t1,t2});
//While is not empty process the nodes
while(!st.isEmpty()) {
TreeNode[] curr = st.pop();
//Process the node
curr[0].val+=curr[1].val;
//1. curr[0] = null, curr[1] != null -> curr[1]
//2. curr[1] = null, curr[0] != null -> curr[0]
//3. both not null, add it stack
//Left Tree
if(curr[0].left == null) {
curr[0].left = curr[1].left;
}
else if(curr[1].left != null) {
st.push(new TreeNode[]{curr[0].left, curr[1].left});
}
//Right Tree
if(curr[0].right == null) {
curr[0].right = curr[1].right;
}
else if(curr[1].right != null) {
st.push(new TreeNode[]{curr[0].right, curr[1].right});
}
}
return t1;
}
}
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
//If t1 == NULL -> t2
//If t2 == NULL -> t2
// Sum (t1,t2)
if(t1 == null) return t2;
if(t2 == null) return t1;
Queue<TreeNode[]> q = new LinkedList<>();
q.add(new TreeNode[]{t1,t2});
//While is not empty process the nodes
while(!q.isEmpty()) {
TreeNode[] curr = q.remove();
if(curr[1] != null) {
curr[0].val+=curr[1].val;
//1. curr[0] = null -> curr[1]
//2. curr[0] = null ->, add it queue
//Left Tree
if(curr[0].left == null) {
curr[0].left = curr[1].left;
}
else {
q.add(new TreeNode[]{curr[0].left, curr[1].left});
}
//Right Tree
if(curr[0].right == null) {
curr[0].right = curr[1].right;
}
else {
q.add(new TreeNode[]{curr[0].right, curr[1].right});
}
}
}
return t1;
}
}