将节点正确插入C 中的BST



我正在研究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();
};

(我知道我不是一贯的卷曲。对不起。)

命名惯例将挽救您的生命!看来您通过将根既是成员又是参数来射击了自己。

最新更新