二叉搜索树在字符串中阅读?C++

Binary Search Tree reading in Strings? C++

本文关键字:C++ 字符串 搜索树      更新时间:2023-10-16

我有一个项目将于周一晚上到期。该项目是实现一棵红黑树,在独立宣言中读作"独立.txt",并将这些字符串放入一棵红黑树中。我正在尝试首先将其实现为二叉搜索树,然后添加颜色和旋转,因为我已经制定了该代码。

面临的问题是,现在我不断收到以下错误:"错误 C2660"'RBT ::插入':函数不接受 1 个参数"和"智能感知:从"std:string"到"RBT::RBTNode *"的不合适转换函数存在",然后是 IntelliSense:函数调用中指向行根的参数太少。插入(我的字符串);

我还需要帮助将文件读入二叉搜索树。我确实认为我的插入方法是正确的,问题出在主方法上。

感谢我被困住时的任何帮助。

#include "stdafx.h" 
#include <iostream>
#include <fstream>
#include <string> 
using namespace std; 
template<typename T>
class RBT
{
    struct RBTNode {
        T data;
        RBTNode* left;
        RBTNode* right;
    };
public:
    RBT();
    ~RBT();
    void GetNewNode(RBTNode* root, T data);
    void Insert(RBTNode* root, T data);
    bool Search();
    void Display();
};

template <typename T>
void RBT<T>::GetNewNode(RBTNode* root, T data) {
    RBTNode* newNode = new RBTNode();
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
template <typename T>
void RBT<T>::Insert(RBTNode* root, T data) {
    if (root == NULL) {
        root = GetNewNode(data);
    }
    else if (data <= root->data) {
        root->left = Insert(root->left, data);
    }
    else {
        root->right = Insert(root->right, data);
    }
    return root;
} 
template<typename T>
bool RBT<T>::Search() {
    if (root == NULL) return false;
    else if (root->data == data) return true;
    else if (data <= root->data) return Search(root->left, data);
    else return Search(root->right, data);
}
template<typename T>
void RBT<T>::Display() {
    if (root->left != NULL)
        display(root->left);
    cout << root->left << endl;
    if (root->right != NULL)
        Display(root->right);
    cout << root->right << endl;
}

int main()
{
    RBT<string> root;
    string myString; 
    ifstream infile; 
    infile.open("Independence.txt"); 
    while (infile)
    {
        infile >> myString; 
        root.Insert(myString); 
    }
    cin.ignore();
    return 0;
}

您的Insert方法需要 2 个参数(要插入的根和要插入的数据);在 main 中,您只用 1(数据)调用它。