How do I make a BST when I have an array list of 100 elements like {3,2,6,7,...,99}
?
A binary search tree, also known as ordered binary tree is a binary tree wherein the nodes are arranged in a order. The order is : a) All the values in the left sub-tree has a value less than that of the root node. b) All the values in the right node has a value greater than the value of the root node.
I believe TreeSet
is an implementation of a binary search tree. Since integers have a natural ordering you could simply loop through your array of integers and add them all to a TreeSet<Integer>
.
Note also, that there is a method Arrays.binarySearch
that does a binary search in a sorted array.
int[] someInts = {3,2,6,7, /*...,*/ 99};
// use a TreeSet
TreeSet<Integer> ints = new TreeSet<Integer>();
for (int i : someInts)
ints.add(i);
System.out.println(ints.contains(2)); // true
System.out.println(ints.contains(5)); // false
// or sort the array and use Arrays.binarySearch
Arrays.sort(someInts);
System.out.println(Arrays.binarySearch(someInts, 2) >= 0); // true
System.out.println(Arrays.binarySearch(someInts, 5) >= 0); // false
Unless you want to implement everything yourself (in that case, you might want to check here) you should take a look at [Collections.binarySearch][2].
[2]: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#binarySearch(java.util.List, java.lang.Object)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With