# Building a binary search tree

• November 27th, 2011, 02:35 PM
Herah
Building a binary search tree
I am working on a program that creates several lists of random numbers, then runs sort algorithms on them and tracks the time it takes them to run. I've had no trouble building the lists, and running the standard sorts (bubble, merge, insert etc).

My problem is that now I am trying to build a binary search tree using my lists, and am really confused. Using my book as a guide I have classes for node and tree basics, but I don't understand how to actually build the tree.

I believe the algorithm needs to be recursive, something like: middle item from list becomes root node, item to left of it is left child, item to right of it is right child.

I'm not sure where to go from there. I don't even know if that will work. Please guide me if you can, I have been stuck on this a few days now.

I can attach the code I already have, but I don't think most of it is relavant as it works fine. I'm pretty sure my brain is turned to jello now, and this part of my code is probably useless.

Code Java:

```public static BinaryTree<Integer> treeBuilder(int arrayStart, int arrayEnd, int arrayMid){   if(!(arrayMid == arrayStart) && !(arrayMid == arrayEnd)){ BT.attachLeft(array[arrayMid - 1]); treeBuilder(0, arrayMid, arrayMid/2); BT.attachRight(array[arrayMid + 1]); treeBuilder(arrayMid+1, array.length, (array.length - arrayMid) / 2); } return BT;     }```
• November 28th, 2011, 06:29 AM
Mr.777
Re: Building a binary search tree
Do you have the concept of Binary Search Tree? If yes, take a pencil and paper, start writing with a sequence of numbers and try to apply the algorithm on that sequence (step by step)
Write these steps on your paper, implement them programatically. And recursion is not the only solution for this, i must tell you.