Hey so I am attempting to write a BST but I am having a lot of errors and I am pretty overwhelmed and lost on what to do. Can you guys take a look and point out anything that is off. The teacher wasn’t very useful at all at explaining anything.
header in the .h file
class Tree
{
public:
bool insert(int k, string s);
private:
struct Node
{
int key;
string data;
Node *left;
Node *right;
};
Node* root;
bool insert(Node *& root, int k, string s);
};
the .cpp file
bool Tree::insert(int k, string s)
{
return insert(root, k, s);
}
bool Tree::insert (Node *& root, int k, string s)
{
if (root == NULL){
root = new Node;
root->key = k;
root->data = s;
root->left = NULL;
root->right = NULL;
}
else if (root == k)
return false;
else if (root->key < k)
insert (root ->left, k);
else
insert (root -> right, k);
}
It appears that you have a lot of untested code. You will have to get the features working one at a time.
Furthermore, I see at least one instance of duplicated effort already. The
preOrderandpostOrdermethods should be slight variations of the same algorithm, yet one is loop-based and the other works by function recursion.Set these source files aside, create a new project, and copy-paste over one feature at a time. Test thoroughly before moving on to the next feature. If you reach a feature that might already be latent in the existing code, don’t copy-paste from the old code, but instead leverage the existing tested code.
Edit
That looks like it should work. Here are a couple stylistic criticisms, if you want them :v) .
Nodestructure should have its own constructor. Always provide a constructor to help guarantee that nothing can be in an invalid state.roottoNULLwhen you create a newTree.rootargument is not good style. At first glance, it looks likeleftandrightnever receive non-NULLvalues. Personally I favor a pointer-to-pointer here, but some might agree with your implementation instead.