В чем проблема в этом BST-код?Когда я ввожу данные первого узла, это дает мне ошибку и не идет дальше - PullRequest
0 голосов
/ 24 сентября 2018
     in this code node structure and insertion and inorder traversal code has 
    been written and whenever i compile this code it doesn't give me any error 
    or exception but when i run this code this only takes one input and then 
    show me that there is an error thats why it can not be continued further. 
#include <iostream>

using namespace std;

struct node //structure for node

{

    int data;

    node *left;

    node *right;

};
     in this code node structure and insertion and inorder traversal code has 
    been written and whenever i compile this code it doesn't give me any error 
    or exception but when i run this code this only takes one input and then 
    show me that there is an error thats why it can not be continued further.
class bst

{

    public:

        node *root;

        node *temp;

        int key;

        bst()

        {

            root = temp = NULL;

            key = 0;

        }

        bst insertion(node*); 
Kindly oversee this function and tell me 
what is the error in this function and the function of inorder

        bst inorder(node*);

};

bst bst::insertion(node *temp) this function is for insertion

{

    if(root==NULL) check if the root is null

    {

        cout<<"Enter Root Ki info:"<<endl;

        cin>>root->data;

        root->left = root->right = NULL;

    you must say that i should return over here but the return function 
    can not be available here and i am unable to correct this one.

    }

    cout<<"Enter Data:"<<endl;

    cin>>key;

    if(key>root->data) check if key is greater than the root's data

    {

        temp->right = new node;  it makes new node from right

        temp->right->data= key;

        temp->right->left = NULL;

        temp->right->right = NULL;
if i return temp over here it says me that this can not be done because of the node * pointer can not be converted into bst pointer and etc.
    }

    else if(key<root->data)  check if key is below than the root'data

    {

        temp->left = new node;

        temp->left->data = key;

        temp->left->left = NULL;

        temp->left->right = NULL;

    }

}

bst bst :: inorder (node ​​* temp) эта функция используется для отображения сведений об узле в схеме inorder

{

    if(root==NULL)

    {

        cout<<"Nothing to be found"<<endl;

    }
     this is for inorder in which the the root element will be shown after the left nodes and at the end right nodes of the root will be shown and similarly post and preorder traversal can be done but this is not showing me any thing can you describe what will be the exact reason and i have tried to oversee all the elements by varying the pointer of struct in the main call but it doesn't make any difference
    inorder(temp->left);

    cout<<temp->data<<'\t';

    inorder(temp->right);

это для порядка, в котором корневой элемент будет показан после левых узлов и в конце будут показаны правые узлы корня, и аналогичным образом можно выполнить обход и предварительный заказ, но это не показывает мне ничего, что вы можете описатькакова будет точная причина, и я попытался контролировать все элементы, изменяя указатель структуры в главном вызове, но это не имеет никакого значения}

это для порядка, в котором корневой элементбудет показан после того, как левые узлы и в конце будут показаны правые узлы корня, и аналогичным образом может быть выполнен обход и предварительный заказ, но это не показывает мне ничего, вы можете описать точную причину, и я попыталсяконтролировать все элементы, изменяя указатель структуры в главном вызове, но это не имеет значения int main ()

{

    bst b;

    for(int i=0;i<5;i++)

    {

        b.insertion(b.root); error occurs when this is running



    }

    b.inorder(b.root);  it doesn't reach till this point

    system("Pause");
it is demanding more and more detail all is this what should i describe moe kindly tell me that also [enter link description here][1]

}

Ответы [ 2 ]

0 голосов
/ 24 сентября 2018

// это окончательный код, и ответ для всего кода выполняется правильно и всегда дает правильный ответ, как и должно быть #include using namespace std;структура узел {узел * слева;узел * справа;int data;};класс bst {public: node * root;узел * темп;bst () {temp = root = NULL;

    }
    void insertion(node*,int key);
    void inorder(node *);
};
void bst::insertion(node *temp,int key)
{
    if(root==NULL)
    {
        temp = new node;
        temp->data = key;
        temp->left = NULL;
        temp->right = NULL;
        root = temp;
        return;
    }
     else if(key<root->data)
    {
        if(temp->left!=NULL)
        {
        insertion(temp->left,key);
        return;
        }
        else
        {
         temp->left = new node;
         temp->left->data = key;
         temp->left->left = NULL;
         temp->left->right = NULL;
         return;
        }
     }
     else if(key>root->data)
    {
        if(temp->right!=NULL)
        {
            insertion(temp->right,key);
            return;
        }
        else
        {
        temp->right = new node;
        temp->right->data = key;
        temp->right->left = NULL;
        temp->right->right = NULL;
        return;
        }
    }

}
void bst::inorder(node *temp)
{

    if(root==NULL)
    {
        return;
    }
    if(temp->left!=NULL)
    inorder(temp->left);
    cout<<temp->data<<'\t';
    if(temp->right!=NULL)
    inorder(temp->right);
}

int main()
{
    bst b;
    int choice;
    char ch;
    char c;

    do{
        cout<<"enter 1 for insertion and 2 to show BST and 3 to delete node: "<<endl;
        cin>>ch;
        switch(ch)
        {
            case'1':
                cout<<"enter no you want to insert in bst: "<<endl;
                cin>>choice;

                b.insertion(b.root,choice);
                break;
            case'2':
                cout<<endl;
                cout<<"The data in BST: "<<endl;
                b.inorder(b.root);
                break;
        }

        cout<<"press y or Y for another insertion: "<<endl;
        cin>>c;
    }while(c == 'y' || c == 'Y' );
}
0 голосов
/ 24 сентября 2018

Извините, но в этом коде не так уж много правильного.

Дизайн неправильный.Вам нужно запросить ключ в главной функции, а затем передать ключ методу insertion в качестве параметра.Не имеет смысла передавать временный узел в качестве параметра.Если insertion нужен временный узел, он должен создать его для себя.

Также insertion не нужно возвращать BST, ему нужно только изменить BST, на который указывает указатель this.Так что insertion должно выглядеть примерно так

void bst::insertion(int key) {
    ...
}

И main должно выглядеть примерно так

int main()
{
    bst b;
    for (int i = 0; i < 5; i++)
    {
        cout << "enter data";
        int key;
        cin >> key;
        b.insertion(key);
    }
    b.inorder();
}

Метод bst::inorder имеет похожие ошибки.

Также bstне нуждается в переменных-членах для ключа и временного узла.Так что удалите

int key;
node *temp;

из class bst.Если вам нужны эти переменные в методе, тогда объявите их в методе, не в классе.Единственное, что нужно классу - это указатель на корень.

Алгоритм в insertion неверен.Для добавления узла в BST требуется какой-то цикл .Вы должны перебирать дерево, пока не доберетесь до свободного слота, только тогда вы сможете вставить узел.Ваш insertion код не имеет цикла, поэтому он не может быть правильным.

Наконец, причина сбоя вашего кода здесь

if(root==NULL)
{
    cout<<"Enter Root Ki info:"<<endl;
    cin>>root->data;

Если root равен NULL, тогда root->data - ошибкаи может привести к сбою вашей программы.

Слишком много проблем с этим кодом.Я думаю, вам нужно лучше понять, как проектировать классы, прежде чем пытаться их кодировать.К сожалению.

...