Reputation: 105
I have the following code to work with, how could make this method create a BST. I am working Elements.I am using custom imports that can do "T.setRoot()","n.getRightChild()","n.setLeftChild()" and so on, which shouldn't be too hard to figure out.
public static <E> BTree<E> taulukostaPuu(ArrayList<E> L) {
BTree<E> T = new BTree<E>();
//TODO
return T;
}
How could i make a recursive method to go through the Arraylist of elements and add them do the BST. I would like to keep this structure intact. All the examples i found were used while the arraylist contained integers, that makes implementing them in element form very difficult. The BST has to be balanced.
I have tried to following:
private static <E> BTree<E> buildRecursively(ArrayList<E> L,E start,E
end,BTree<E> T){
if (start.compareTo(end) < 0)
return T;
E x = L.get((L.size()/2) + (L.size() % 2));
T.setRoot(new BTreeNode<E>(x));
T.setLeftChild(buildRecursively(L, start, L.get((L.size()/2) + (L.size()
% 2)-1)),T);
T.setRightChild(buildRecursively(L, L.get((L.size()/2) + (L.size() %
2)+1),
L.get(L.size()-1)),T);
But this obviously this didnt work.
This is what i am currently working with:
public static <E> BTree<E> taulukostaPuu(ArrayList<E> L) {
BTree<E> T = new BTree<E>();
E root = L.get((L.size()/2) + (L.size() % 2));
T.setRoot(new BTreeNode<E>(root));
return T;
}
Not sure where to go from here. I am supposed to somehow traverse the arraylist from x to find the element for the 2 children and do that recursively. Any suggestions?
Upvotes: 0
Views: 678
Reputation: 34
Have you checked this click here it's a good start to understand BST, in case you talk about simple BST.
Upvotes: 1