I am trying to create a binary search tree with an emphasis on recursion and am currently stuck on creating a function to return an arraylist of the elements of the the binary search tree in order.
My main problem is moreso how to implement this algorithm into a function that returns an arraylist.
Here is the beginning of the class:
public class BinarySearchTree<T> {
private Comparator<T> comparator;
private T data;
private BinarySearchTree<T> left;
private BinarySearchTree<T> right;
This is the function I current have:
public List<T> getElements() {
List<T> list = new ArrayList<>();
if(data != null) {
left.getElements();
list.add(data);
right.getElements();
}
return list;
}
Here is my insert function, which I believe is correct but if the problem is rooted here, it may help debugging:
public void insert(T element) {
if(data == null) {
data = element;
}
if(element != null && data != null) {
if(comparator.compare(element, data) == -1) {
if(left == null) {
left = new BinarySearchTree<T>(element, comparator);
}
else {
left.insert(element);
}
}
if(comparator.compare(element, data) == 1) {
if(right == null) {
right = new BinarySearchTree<T>(element, comparator);
}
else {
right.insert(element);
}
}
if(comparator.compare(element, data) == 0) {
return;
}
}
You need to add the results from your recursive calls to getElements
to list
(which, by the way, is a really bad name).
Also, you'll need to consider how to handle the cases where either left
and/or right
is null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.