Reputation: 697
I'm writing a program that takes input from a txt file then inputs it into a BST (then manipulates the data, etc.)
What's happening is the data file is read properly, it goes to the Insert function, "writes" the info, but the root NODE remains NULL.
Code:
#include <iostream>
#include <string>
using namespace std;
class BST {
private:
struct NODE {
int ID;
string name;
float balance;
NODE *left;
NODE *right;
};
NODE *root;
void Insert(NODE* &p, int x, float balance, string name) {
NODE* q;
if (p == NULL) {
q = new NODE;
q -> ID = x;
q -> name = name;
q -> balance;
q -> left = NULL;
q -> right = NULL;
p = q;
} else {
if (x < p -> ID) {
Insert(p -> left, x, balance, name);
} else {
Insert(p -> right, x, balance, name);
}
}
}
void DisplayInorder(NODE * p) {
if (p != NULL) {
DisplayInorder(p -> left); // LC
cout << p -> ID << "\t" << p->name << "\t" << p -> ID << endl; // P
DisplayInorder(p -> right); // RC
}
}
void DisplayRecord(NODE * p, int x, bool& found) {
if (p != NULL) {
DisplayRecord(p -> left, x, found); // LC
if (x == p->ID) {
found = true;
}
DisplayRecord(p -> right,x, found); // RC
}
}
public:
BST() {
root = NULL;
}
void Insert(int x, float balance, string name) {
Insert(root, x, balance, name);
}
void DisplayInorder() {
DisplayInorder(root);
}
void DisplayRecord(int x, bool& found){
DisplayRecord(root, x, found);
}
};
Calling statements:
void Initialize(BST tree) {
fstream f;
f.open("data.txt",ios::in);
do {
int ID = 0;
float balance = 0;
string name = "NULL";
f >> ID >> name >> balance;
tree.Insert(ID,balance,name);
} while(f.eof() == false);
f.close();
}
Is it perhaps because the BST tree object needs to be passed by reference?
Upvotes: 0
Views: 143
Reputation: 36082
The Initialize function takes a 'BST tree' as argument however whatever changes you do to 'tree' will have local function scope only since 'tree' is a copy.
change
void Initialize(BST tree)
to
void Initialize(BST& tree)
Upvotes: 0
Reputation: 409136
Yes, the tree needs to be passed by reference. Right now you're making a copy, and only insert in the copy. The original tree, that you have in the function where you call Initialize
from, will not change.
Upvotes: 1