-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1305-AllElementsInTwoBinarySearchTrees.java
More file actions
47 lines (37 loc) · 1.08 KB
/
Copy path1305-AllElementsInTwoBinarySearchTrees.java
File metadata and controls
47 lines (37 loc) · 1.08 KB
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
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> res = new ArrayList<>();
List<Integer> left = new ArrayList<>();
left = inorder(root1, left);
List<Integer> right = new ArrayList<>();
right = inorder(root2, right);
int i = 0;
int j = 0;
while (i < left.size() && j < right.size()) {
if (left.get(i) <= right.get(j)) {
res.add(left.get(i));
i += 1;
} else {
res.add(right.get(j));
j += 1;
}
}
while (i < left.size()) {
res.add(left.get(i));
i += 1;
}
while (j < right.size()) {
res.add(right.get(j));
j += 1;
}
return res;
}
private List<Integer> inorder(TreeNode root, List<Integer> list) {
if (root == null)
return list;
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
return list;
}
}