Hey everyone,
So, for my C++ course I am implementing a Binary Search Tree. In this Binary Search Tree we are to create a function to copy the values of a passed array into a Balanced Binary Search Tree that will render a correct inorder traversal.
I.E. an array of 0, 1, 2 will be in the tree in Root->1, Left->0, Right->2
I think I'm pretty close to figuring out the function (which is good considering how long I've been working on it;) ). However, I'm having issues on figuring out not only my base case, but also if passing mid in is the correct way to go about "altering" my values.
I know line 25 is wrong, as well as (I think) line 20 but I'm not sure where to go from here...Any help would be greatly appreciated!
PS: The while loop in the first function is to find out what the highest subscript with a stored value in the array is. We are guaranteed to be passed a statically allocated array of 99 elements, but we have to find out how many elements are in the array. Thus the loop.
//------------------------------ arrayToBSTree --------------------------------
void BSTree::arrayToBSTree(NodeData *data[]) {
this->makeEmpty();
int i = 0;
int high = i;
while(data[i] != NULL && i <= 99) {
high = i;
i++;
}
this->overallRoot = toTreeHelper(data, 0, high, this->overallRoot);
}
//------------------------------ toTreeHelper ---------------------------------
BSTree::Node* BSTree::toTreeHelper(NodeData *data[], int low, int high,
Node *root) {
int mid = (low + high) / 2;
root = new Node;
root->left = root->right = NULL;
root->data = NULL;
if(mid != 0) {
root->left = toTreeHelper(data, low, mid, root->left);
}
root->data = data[mid];
data[mid] = NULL;
if(mid != 0 || mid != high - 1) {
root->right = toTreeHelper(data, mid + 1, high, root->right);
}
return root;
}