如何使用二叉搜索树的索引生成器解决此问题

How can i fix this problem with index builder using binary search tree?

本文关键字:解决 问题 索引 何使用 搜索树      更新时间:2023-10-16

>我有一个任务,就是编写一个索引生成器应用程序,它接受由行组成的文本并打印文本的单词列表,它们出现在它们旁边的行。

但是当我尝试处理这种情况时,如果单词已经存在,我遇到了一个问题,它总是在向量中添加一个冗余数字

谁能帮我?

这是BSTnode的定义:

class BSTnode
{
public:
    string data;
    vector<int> linesAppear;
    BSTnode* left;
    BSTnode* right;
    BSTnode()
    {
        left = right = NULL;
    }
};

这是BSTFCI的定义:

class BSTFCI
{
public:
    BSTnode* root;
    BSTFCI()
    {
        root = NULL;
    }
    void add(string ToBST,int lineAppear);
    BSTnode* Insert(BSTnode*& node,string ToBST,int lineAppear);
    BSTnode* create_new_node(string ToBST,int lineAppear);   
};

插入功能

BSTnode* BSTFCI::create_new_node(string ToBST,int lineAppear)
{
    BSTnode* Temp = new BSTnode();
    Temp->data = ToBST;
    Temp->left = Temp->right = NULL;
    Temp->linesAppear.push_back(lineAppear);
    return Temp;
}
BSTnode* BSTFCI::Insert(BSTnode*& node,string ToBST,int lineAppear)
{
    if(node == NULL)
    {
        node = create_new_node(ToBST,lineAppear);
    }
    if(ToBST > node->data)
    {
        node->right = Insert(node->right,ToBST,lineAppear);
    }
    if(ToBST < node->data)
    {
        node->left = Insert(node->left,ToBST,lineAppear);
    }
    //cout <<"inside insert"<< ToBST << endl;
    if(node->data == ToBST)
    {
        node->linesAppear.push_back(lineAppear);
     //   cout <<"inside insert condition "<< node->data << endl;
    }
    return node;
}
void BSTFCI::add(string ToBST,int lineAppear)
{
    root = Insert(root,ToBST,lineAppear);
}

主要功能:

int main()
{
    BSTFCI o;
    string input,ToBST;
    int lineAppear = 0;
    while(getline(cin,input))
    {
        if(input == "done")
        {
            break;
        }
        lineAppear++;
        istringstream convert(input);
        while(convert >> ToBST)
        {
            o.add(ToBST,lineAppear);
        }
    }
    o.print_inOrder(o.root);
    return 0;
}

这是因为您在 create_new_node 中添加了数字(实际上应该是 BSTnode 中的构造函数(稍后if(node->data == ToBST)

您需要决定是在创建节点时还是之后添加它,但在创建时执行此操作最有意义 - 为什么要添加节点而不给它一个发生?

我会这样做:

class BSTnode
{
public:
    string data;
    vector<int> linesAppear;
    BSTnode* left;
    BSTnode* right;
    BSTnode() : left(nullptr), right(nullptr) {}
    BSTnode(const std::string& word, int appearance) 
        : data(word),
          linesAppear(1, appearance),
          left(nullptr),
          right(nullptr)
    {
    }
};

BSTnode* BSTFCI::Insert(BSTnode* node, string ToBST,int lineAppear)
{
    if(node == nullptr)
    {
        return new BSTnode(ToBST, lineAppear);
    }
    if(ToBST > node->data)
    {
        node->right = Insert(node->right, ToBST, lineAppear);
    }
    else if(ToBST < node->data)
    {
        node->left = Insert(node->left, ToBST, lineAppear);
    }
    else
    {
        node->linesAppear.push_back(lineAppear);
    }
    return node;
}

请注意,通过引用传递node返回都没有意义,因此我保留了返回并删除了引用。
你也可以反其道而行之。