我正在使用BST从文件中添加浮点数。在编写代码时,它每次都会添加一个新根,因为根目录未正确添加和更新。我无法弄清楚我做错了什么。感谢任何帮助,谢谢!
这是我的创建和添加功能:
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);
}
}
}
}
我的构造函数:
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();
};
(我知道我并不是一直都在鼓掌。抱歉。)
答案 0 :(得分:2)
命名约定将拯救你的生命!看来你通过使root成为成员和参数来射击自己。