繁体   English   中英

二进制搜索树仍然为空?

[英]Binary Search Tree remains empty?

我正在编写一个程序,该程序从txt文件中获取输入,然后将其输入到BST中(然后处理数据等)。

发生的情况是正确读取了数据文件,将其转到Insert函数,“写入”了信息,但是根节点NODE仍然为NULL。

码:

#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);
    }


};

调用语句:

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();
}

可能是因为BST树对象需要通过引用传递吗?

是的,该树需要通过引用传递。 现在,您正在制作副本,并且只能插入副本中。 您在调用Initialize from的函数中拥有的原始树不会更改。

Initialize函数采用“ BST树”作为参数,但是对“ tree”所做的任何更改都将具有局部函数作用域,因为“ tree”是副本。

更改

void Initialize(BST tree) 

void Initialize(BST& tree)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM