-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAll Elements in Two Binary Search Trees
44 lines (43 loc) · 1.22 KB
/
All Elements in Two Binary Search 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
/**
* 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 {
List<Integer> tree1 = new ArrayList<>();
List<Integer> tree2 = new ArrayList<>();
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
inorder(root1, tree1);
inorder(root2, tree2);
tree1.add(Integer.MAX_VALUE);
tree2.add(Integer.MAX_VALUE);
List<Integer> res = new ArrayList<>();
int i = 0;
int j = 0;
while(res.size()!=tree1.size() + tree2.size()-2){
if(tree1.get(i) < tree2.get(j)){
res.add(tree1.get(i++));
}
else{
res.add(tree2.get(j++));
}
}
return res;
}
public void inorder(TreeNode root, List<Integer> tofill){
if(root == null) return;
inorder(root.left, tofill);
tofill.add(root.val);
inorder(root.right, tofill);
}
}