Create a binary tree class. -Data array field (private) -Count field Add method(
ID: 3588466 • Letter: C
Question
Create a binary tree class. -Data array field (private) -Count field Add method(data) -The add method takes a data point, add it to the count position in the array then increases the count. Print method(void) -Prints all the fields in the tree.In java or c++ Create a binary tree class. -Data array field (private) -Count field Add method(data) -The add method takes a data point, add it to the count position in the array then increases the count. Print method(void) -Prints all the fields in the tree.
In java or c++ Create a binary tree class. -Data array field (private) -Count field Add method(data) -The add method takes a data point, add it to the count position in the array then increases the count. Print method(void) -Prints all the fields in the tree.
In java or c++
Explanation / Answer
In java!
/**
*
* @author Sam
*/
public class BST<data extends Comparable<data>> {
private data[] array;
int count;
public BST() {
array =(data[]) new Object[15];
count = 0;
}
public void add(data d){
int tmp = 0;
while (tmp < array.length && array[tmp] != null) {
if (array[tmp].compareTo(d) < 0)
tmp = tmp*2 + 2; //right child node
else
tmp = tmp*2 + 1; //left child node
}
if (tmp >= array.length){
data[] tmpArray = (data[])new Object[array.length*2];
System.arraycopy(array, 0, tmpArray, 0, array.length);
array = tmpArray;
}
array[tmp] = d;
count++;
}
public void print() {
for (data item : array) {
if (item != null) {
System.out.println(item);
}
}
}
}