I'm trying to write a function that recursively goes through an array, inserting values into a tree while keeping the tree balanced. It's assumed that the array is sorted and that we know its size. I understand that what I need to do is begin from around the middle of the array, insert that value into the root, then take the middle of the left and right halves and insert those into nodes left and right of the root, and so on until the array is filled. Recursion is the first thing that comes to mind and what I coded makes sense, but it doesn't seem to be working the way I intended.
Issues I'm having are that the first and last values are not being inserted, and I'm getting nodes with garbage values at the left and right of each leaf, instead of them being NULL.
The structure of the node is simple(provided by instructor):
/* A lightweight structure implementing a general binary tree node */
template <class T>
struct BTNode {
T elem; // element contained in the node
BTNode *left; // pointer to the left child (can be NULL)
BTNode *right; // pointer to the right child (can be NULL)
// Constructors
BTNode() { left = right = NULL; }
BTNode( T elem, BTNode* left = NULL, BTNode* right = NULL ) {
this->elem = elem;
this->left = left;
this->right = right;
}
BTNode( const BTNode& src ) {
this->elem = src.elem;
this->left = src.left;
this->right = src.right;
}
// Simple tests
bool is_leaf() const { return (left == NULL && right == NULL); }
};
This is the function I wrote:
// ---------------------------------------------------------------------------
// Constructor (from sorted array)
//
template<class T>
BinarySearchTree<T>::BinarySearchTree(T *elements, int n_elements) {
int high = n_elements-1;
int low = 0;
root = new BTNode<T>;
BSTreeHelper(low, high, elements, BinaryTree<T>::root);
}
Helper function for constructor:
template<class T>
void BinarySearchTree<T>::BSTreeHelper(int low, int high, T* elems, BTNode<T>* root) {
int mid = (low+high)/2; // to get the middle value
bool isEqual = (low+1 == high || high-1 == low);
// if there is a middle value, insert it
if (!isEqual) {
BTNode<T>* nodePtrL = new BTNode<T>;
root->left = nodePtrL;
BSTreeHelper(low, mid, elems, nodePtrL);
BTNode<T>* nodePtrR = new BTNode<T>;
root->right = nodePtrR;
BSTreeHelper(mid, high, elems, nodePtrR);
root->elem = elems[mid];
cout << "Inserted Element = " << root->elem << endl;
}
}
I can't seem to wrap my head around doing the isEqual check differently in any way in order to account for the first and last elements, and I'm really not sure why extra nodes are being created with garbage values (values outside the bounds of the array most likely). Thanks for any help you can provide. This is an assignment so I don't want the answer to be given, but a point in the right direction is much appreciated!