Skip to content

Commit 44a5a2c

Browse files
committed
compare arrays as the same bst
1 parent 20d8686 commit 44a5a2c

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import java.util.ArrayList;
2+
3+
/**
4+
Given two integer unsorted arrays, your task is to compare the BST formed by both the arrays.
5+
6+
e.g [3 2 1 0 5 4 6] & [3 5 2 6 4 1 0]
7+
when the BST is formed by taking the elements from the left, both BST turn out to be same.
8+
9+
3
10+
/ \
11+
2 5
12+
/ \ / \
13+
1 0 4 6
14+
15+
Expected time complexity O(n).
16+
17+
*/
18+
public class CompareArrayBST {
19+
public static void main(String[] args){
20+
21+
int[] a1 = new int[]{3,2,1,0,5,4,6};
22+
int[] a2 = new int[]{3,5,2,6,4,1,0};
23+
24+
boolean same = identicalBST(a1, a2);
25+
26+
System.out.println(same);
27+
28+
int[] b1 = new int[]{3,2,1,0,5,4,6};
29+
int[] b2 = new int[]{3,6,2,5,4,1,0};
30+
31+
boolean same1 = identicalBST(b1, b2);
32+
33+
System.out.println(same1);
34+
}
35+
public static boolean identicalBST(int[] a, int[] b ){
36+
if(a.length != b.length)
37+
return false;
38+
if(a.length == 0)
39+
return true;
40+
if(a.length == 1 && a[0]==b[0])
41+
return true;
42+
if(a[0] != b[0])
43+
return false;
44+
45+
ArrayList<Integer> aSmaller = new ArrayList<Integer>();
46+
ArrayList<Integer> aLarger = new ArrayList<Integer>();
47+
ArrayList<Integer> bSmaller = new ArrayList<Integer>();
48+
ArrayList<Integer> bLarger = new ArrayList<Integer>();
49+
50+
for(int i = 1; i < a.length;i++){
51+
if(a[i] < a[0])
52+
aSmaller.add(a[i]);
53+
else
54+
aLarger.add(a[i]);
55+
}
56+
57+
for(int i = 1; i < b.length;i++){
58+
if(b[i] < b[0])
59+
bSmaller.add(b[i]);
60+
else
61+
bLarger.add(b[i]);
62+
}
63+
64+
return ( identicalBST(convertIntArray(aSmaller), convertIntArray(bSmaller))
65+
&& identicalBST(convertIntArray(aLarger), convertIntArray(bLarger)) ) ;
66+
}
67+
68+
public static int[] convertIntArray(ArrayList<Integer> integers)
69+
{
70+
int[] ret = new int[integers.size()];
71+
for (int i=0; i < ret.length; i++)
72+
{
73+
ret[i] = integers.get(i).intValue();
74+
}
75+
return ret;
76+
}
77+
}

0 commit comments

Comments
 (0)