在字符串中读取二进制搜索树? C ++

时间:2014-12-07 15:24:28

标签: c++ string binary-search-tree red-black-tree

我有一个项目将于周一晚上到期。该项目将实现一个红黑树,它将独立声明读作“Independence.txt”并将这些字符串放入一棵红黑树中。我试图首先将它实现为二进制搜索树,然后将添加颜色和旋转,因为我已经有了代码。

我面临的问题是,现在我不断收到以下错误:“错误C2660”'RBT :: Insert':函数不带1个参数“和”IntelliSense:非合适的转换函数来自“std:string “to”RBT :: RBTNode *“存在”,然后是IntelliSense:函数调用中的参数太少,指向行root.Insert(myString);

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

感谢您的帮助,因为我被困住了。

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

1 个答案:

答案 0 :(得分:2)

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