I wish to iterate over a sorted array in the order that a breadth first traversal would give if I put the array into a binary tree and performed a BFT on that (which is how I currently achieve this). Obviously this involves additional memory overhead since you need to build and store the array again in the binary tree. I know this should be similar to a binary search but I can't quite get the ordering right.
Here's how I currently achieve this:
BTree bst = sortedArrayToBST(array);
Queue<BTree> queue = new LinkedList<BTree>();
queue.add(bst);
while(!queue.isEmpty()) {
BTree node = queue.remove();
System.out.println(node.data);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
Here's what I have currently (but this obviously gives the wrong ordering):
public void bstIterate(int[] array, int start, int end) {
if(array.length == 0) return;
int med = array.length /2;
System.out.println(array[med]);
bstIterate(array,start,mid);
bstIterate(array,mid+1,array.length);
}
Can this be done without extra memory overhead, or do I have to store the items in a stack, vector or queue, and if so, how and would it require less memory than a binary tree?