prichey
prichey

Reputation: 75

Correctly inserting nodes into a BST in C++

I'm working on a BST to add floats from a file. As the code is written, it adds a new root each time because the root is not added and updated correctly. I can't figure out what I'm doing wrong. Any help is appreciated, thanks!

Here's my create and add functions:

void BST::create() {
    string filename;
    ifstream file;
    float value;
    cout << "Enter the file name: ";
    if (getline(cin,filename)) {
        filename.insert(0, "C:/Temp/");
        file.open(("C:/Temp/%s",filename).c_str());
        if (!file) {
            cout << "Error opening file. Make sure it's located in c:/Temp and try again." << endl;
        }
        else if (file) {
            if (file >> value) {
                while(file >> value) {
                    addNode(this->root, value);
                }
                file.close();
            }
            else {cout << "No floats found." << endl;}
        }
    } else { cout << "Error. Please try again." << endl; }
}

void BST::addNode(Node *root, float val) {
    if (root == NULL) {
        root = new Node;
        root->key = val;
        root->leftChild = NULL;
        root->rightChild = NULL;
        cout << "added root" << endl;
        cout << "value is " << root->key << endl << endl;
    } 
    else {
        cout << "root value is " << root->key << endl;
        if (val < root->key) {
            if (root->leftChild == NULL) {
                cout << "adding left child " << val << endl;
                Node *tmp = new Node;
                tmp->key = val;
                tmp->parent = root;
                root->leftChild = tmp;
            } else {
                addNode(root->leftChild, val);
            }
        } 
        else {
            if (root->rightChild == NULL) {
                cout << "adding right child " << val << endl;
                Node *tmp = new Node;
                tmp->key = val;
                tmp->parent = root;
                root->rightChild = tmp;
            } 
            else {
                addNode(root->rightChild, val);
            }
        }
    }
}

And my constructor:

class BST 
{private:
    Node *root;
    void addNode(Node *root, float val);

 public:
  BST()     // a constructor
  {root = NULL;}

  ~BST();   // a destructor that frees all dynamically allocated spaces for the BST

  void display();
  void create();

};

(I know I'm not consistently curly-bracing. Sorry.)

Upvotes: 3

Views: 324

Answers (1)

aj.toulan
aj.toulan

Reputation: 1432

Naming conventions will save your life! It seems you have shot yourself in the foot by making root both a member and a parameter.

Upvotes: 2

Related Questions