c++ - 如何在二叉搜索树中将字符串和整数作为参数?

标签 c++ data-structures

我是编程界的新手,几天来我一直陷入同样的​​问题。我的任务是创建一个二叉搜索树,它将一个字符串和一个整数作为参数并将这对存储在树中。我的代码适用于字符串但不适用于整数,例如,如果我为字符串输入“John”,为整数输入“2”,它只会输出“John”!我的整个代码如下,让你们了解发生了什么。

BST.cpp:

#include"BST.h"
#include<string>
#include<fstream>

BST::BST()
{
    this->root = NULL;      //root is NULL in the start
}

BST::~BST()
{
    clear(root);            //delete all nodes
}

void BST::clear(Node* current)
{
    if(current == NULL)
        return;

    clear(current->getLeft());          //clear left subtree
    clear(current->getRight());         //clear right subtree
    delete current;                     //delete this node
}

void BST::Insert(string num, int data)
{
    //create new node to be inserted
    Node *n = new Node();
    n->setData(num, data);
    n->setLeft(NULL);
    n->setRight(NULL);


    if(this->root == NULL)      //if root is null, simply add at root
        root = n;

    else
        InsertHelper(root,n);   //call helper to insert
}

void BST::InsertHelper(Node* current, Node* newnode)
{
    if(current == NULL)     
        return;

    //node should be inserted at right subtree
    if(current->getData() <= newnode->getData()){

        //if no node at right
        if(current->getRight() == NULL )    
            current->setRight(newnode);     //add at right node

        else
            InsertHelper(current->getRight(), newnode);     //insert in right subtree
    }
    else{

        if(current->getLeft() == NULL){         //if no node at left
            current->setLeft(newnode);          //add at left
        }else{
            InsertHelper(current->getLeft(), newnode);      //insert in left subtree
        }
    }
}


bool BST::find(string num)
{
    return findHelper(root,num);
}

bool BST::findHelper(Node *current,string num)
{
    if(current == NULL)
        return false;

    if(current->getData() == num)       //if number is founf
        return true;                    

    if(num < current->getData())        //if number is less than current node
        return findHelper(current->getLeft(),num);      //go to left tree
    else
        return findHelper(current->getRight(),num);     //go to right tree
}


void BST::min()
{
    findMinHelper(root);
}

void BST::findMinHelper(Node* current)
{
    if(current == NULL)
        return;

    if(current->getLeft() == NULL)          //if no node at right
        cout<<current->getData();           //current has min data
    else
        findMinHelper(current->getLeft());  //check on left subtree
}

void BST::max()
{
    findMaxHelper(root);
}

void BST::findMaxHelper(Node * current)
{
    if(current == NULL)
        return;

    if(current->getRight() == NULL)             //if no node at right
        cout<<current->getData();               //current node has max data
    else
        findMaxHelper(current->getRight());     //check on right subtree
}

void BST::LoadFromFile(string filename)
{
    ifstream fin;

    fin.open(filename.c_str());         //open input file

    if(fin.fail())
        cout<<"Unable to open input file";
    else{

        string x;
        fin>>x;
        while(!fin.eof())       //while file is not ended
        {
            //  Insert(x);          //insert in tree
            fin >>x;            //read next numbers
        }
        cout<<"Data successfully loaded!!"<<endl;
    }
}

void BST::save_file(string filename)
{
    ofstream fout;
    fout.open(filename.c_str());        //open output file
    saveHelper(fout,root);              //call helper function
    cout<<"Successfully saved\n\n";
}

void BST::saveHelper(ofstream &fout, Node* current)
{
    if(current == NULL)
        return;

    saveHelper(fout,current->getLeft());        //save left tree
    fout<<current->getData() << " ";            //save current data
    saveHelper(fout,current->getRight());       //save right tree
}

void BST::Print()
{
    printHelper(root);
}

void BST::printHelper(Node *current)
{
    if(current == NULL)     //stop if NULL
        return;

    printHelper(current->getLeft());        //print left tree
    cout<<current->getData() << " ";        //print current node data
    printHelper(current->getRight());       //print right tree
}

void BST::Delete(string num){
    root = DeleteHelper(root,num);
}

Node* BST::DeleteHelper(Node *current, string num)
{
    if(current == NULL)
        return NULL;

    Node *tobeReturned;

    if (current->getData() == num) {          //if key is found

        if (current->getLeft() == NULL) {        //no node at left

            tobeReturned = current->getRight();
            delete current;
            return tobeReturned;          //right subtree should replace this node

        } else if (current->getRight() == NULL) {

            tobeReturned = current->getLeft();
            delete current;
            return tobeReturned;
        } else {

            //find maximum node in the left subtree
            Node * maxnode = findMaximum(current->getLeft());

            //copy values from max node to this node
            //      current->setData(maxnode->getData());

            //delete the max node 
            current->setLeft(DeleteHelper(current->getLeft(), num));
        }
        cout<<"Deleted!!!";
    } else {        //not found
        if (num < current->getData()) {
            current->setLeft(DeleteHelper(current->getLeft(),num));
        } else {
            current->setRight(DeleteHelper(current->getRight(), num));
        }
    }
    return current;
}

Node* BST::findMaximum(Node * n)
{
    if(n->getRight() == NULL)       //if no node at right, current is maximum
        return n;
    return findMaximum(n->getRight());      //find in right subtree
}

BST.h:

#ifndef BST_H_
#define BST_H_

#include<iostream>
using namespace std;
#include<string>

#include "Node.h"

//BST class
class BST{

    private:
        Node * root;        //root node pointer

    public:
        BST();                                  //constructor
        ~BST();                                 //destructor
        void Insert(string num, int data);                  //Inserts new number in tree
        bool find(string num);                      //finds whether a number is present in tree
        void min();                             //find and print minimum number in the tree
        void max();                             //find and print maximum number in the tree
        void save_file(string filename);        //save the tree to file
        void Delete(string num);                    //deletes a number from tree
        void LoadFromFile(string filename);     //loads numbers from file to tree
        void Print();                           //print tree to stdout


        //private functions used as helper functions in the public operations
    private:
        void printHelper(Node *root);
        bool findHelper(Node *root,string num);
        void InsertHelper(Node* current, Node* newnode);
        void findMinHelper(Node* current);
        void findMaxHelper(Node * current);
        void saveHelper(ofstream &fout, Node* current);
        Node* DeleteHelper(Node *current, string num);
        Node * findMaximum(Node * n);
        void clear(Node *currnt);
};

#endif

驱动.cpp:

#include"BST.h"
#include<iostream>
using namespace std;

void print_menu()
{
    cout<<"\n\nEnter 1 to Insert new number."<<endl;
    cout<<"Enter 2 to Find number."<<endl;
    cout<<"Enter 3 to Print."<<endl;
    cout<<"Enter 4 to print min."<<endl;
    cout<<"Enter 5 to print max."<<endl;
    cout<<"Enter 6 to save to file."<<endl;
    cout<<"Enter 7 to delete a number."<<endl;
    cout<<"Enter 8 to load data from file."<<endl;
    cout<<"Enter 9 to exit."<<endl;
    cout<<"Enter your choice: ";
}

int main()
{
    bool done = false;
    int choice,data;
    string fname, num;
    BST tree;

    while(!done)
    {
        print_menu();
        cin >> choice;

        switch(choice)
        {
            case 1:
                cout<<"Enter key: ";
                cin >> num;
                cout<<"Enter data:";
                cin >> data;
                tree.Insert(num,data);
                cout<<"Number add successfully"<<endl;
                break;
            case 2:
                cout<<"Enter number: ";
                cin >> num;
                if(tree.find(num))
                    cout<<"Number exists!!"<<endl;
                else
                    cout<<"Number not found"<<endl;
                break;
            case 3:
                tree.Print();
                break;
            case 4:
                tree.min();
                break;
            case 5:
                tree.max();
                break;
            case 6:
                cout<<"Enter filename:";
                cin>>fname;
                tree.save_file(fname);
                break;
            case 7:
                cout<<"Enter number:";
                cin>>num;
                tree.Delete(num);
                break;
            case 8:
                cout<<"Enter filename:";
                cin>>fname;
                tree.LoadFromFile(fname);
                break;
            case 9:
                done = true;
                break;
            default:
                cout<<"Invalid option selected..\n";
                break;
        }
    }

    return 0;
}

节点.cpp:

#include"Node.h"
#include<string>

Node::Node()
{
    this->left = NULL;
    this->right = NULL;
}


void Node::setData(string num, int data)
{
    this->num = num;
}


string Node::getData()
{
    return this->num;
}

void Node::setLeft(Node *l)
{
    this->left = l;
}

Node* Node::getLeft()
{
    return this->left;
}

void Node::setRight(Node *r)
{
    this->right = r;
}

Node* Node::getRight()
{
    return this->right;
}

节点.h:

#ifndef NODE_H_
#define NODE_H_

#include<iostream>
using namespace std;


class Node{

    private:
        int data;                       //number
        Node *left;                     //left child
        Node *right;                    //right child
        std::string num;
    public:
        Node();                         //constructor
        void setData(string num, int data);         //sets number in node
        string getData();                   //return numbers from node
        void setLeft(Node *l);          //sets left child pointer
        Node* getLeft();                //returns left child pointer
        void setRight(Node *r);         //sets right child pointer
        Node* getRight();               //return right child pointer
};


#endif

有人看到我的代码有问题吗?

最佳答案

node.cpp 中,您没有设置整数值

void Node::setData(string num, int data)
{
    this->num = num;
    this->data = data; //missing line!
}

同样在打印的时候,你需要稍微修改一下

cout<<current->getName() << " " << current->getNumber() << " " ;

将这些方法添加到您的 Node 类:getNamegetNumber 分别返回类的字符串和整数。使用它们代替 getData 方法

关于c++ - 如何在二叉搜索树中将字符串和整数作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020281/

相关文章:

c++ - C++调用回调后删除一个对象

java - 枚举外部驱动器

c++ - "macro names must be identifiers"

Python,在二维列表中寻找邻居

algorithm - 总和小于或等于给定 'k' 的子数组数

algorithm - 用 getRandom 设置

C++ 将字符串类型变量中的单词转换为小写

c++ - 数组中的第 K 个和

c++ - 使用指针在常数时间内从集合中删除

c++ - 你如何用 SSE2 处理 exp()?