-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
52 lines (50 loc) · 1.33 KB
/
Solution.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
List<Integer> t1 = new ArrayList<>();
List<Integer> t2 = new ArrayList<>();
dfs(root1, t1);
dfs(root2, t2);
return merge(t1, t2);
}
private void dfs(TreeNode root, List<Integer> t) {
if (root == null) {
return;
}
dfs(root.left, t);
t.add(root.val);
dfs(root.right, t);
}
private List<Integer> merge(List<Integer> t1, List<Integer> t2) {
List<Integer> ans = new ArrayList<>();
int i = 0, j = 0;
while (i < t1.size() && j < t2.size()) {
if (t1.get(i) <= t2.get(j)) {
ans.add(t1.get(i++));
} else {
ans.add(t2.get(j++));
}
}
while (i < t1.size()) {
ans.add(t1.get(i++));
}
while (j < t2.size()) {
ans.add(t2.get(j++));
}
return ans;
}
}