Помогите, пожалуйста, найти ошибку в печати чисел. Если просто выводить массив, то все работает верно, а добавляю число в insert и в print оно исчеза

Рейтинг: -2Ответов: 1Опубликовано: 16.02.2023

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


class Node {
    friend class tree;
    int data;
    Node* l = NULL;
    Node* r = NULL;
    Node* parent = NULL;
    
public:
    Node(int d) :data(d) {};

    int node_get_data() {
        return data;
    }
    Node* node_get_left() {
        return l;
    }
    Node* node_get_right() {
        return r;
    }
    void node_set_left(Node* n) {
        l = n;
    }
    void node_set_right(Node* n) {
        r = n;
    }
    void node_set_data(int n) {
        data = n;
    }
    void node_set_parent(Node* n) {
        parent = n;
    }


};

class tree {
    Node* root = NULL;
public:
    tree(Node* n, int size) {//constructor
        root = n;
        --size;
        insert(n+1, root, size);

    };

    tree(Node n) {// only root there
        root = &n;
    };

    Node* add_elem(Node n) {
        insert(n, root);
        return root;
    }

    Node insert(Node n,Node* current){
        if (root == NULL)
            root = &n;

        if (n.node_get_data() > current->node_get_data())
            if (current->node_get_right() == NULL)
            {
                current->node_set_right(&n);
                current->node_get_right()->node_set_parent(current);
            }
            else insert(n, current->node_get_right());

           
        else if (current->node_get_data() > n.node_get_data())
            if (current->node_get_left() == NULL)
            {
                current->node_set_left(&n);
                current->node_get_left()->node_set_parent(current);
            }
            else insert(n, current->node_get_left());

        return n;
    }

    Node* insert(Node* n, Node* current,int size)// for arrays 
    {

        static int c = 0;
       /*while*/ if (c != size) {
           
            if ((current->node_get_data()) < (n->node_get_data()))
                if (current->node_get_right() == NULL)
                {
                    current->node_set_right(n);
                    current->node_get_right()->node_set_parent(current);
                    ++c;
                    insert(n + 1, root,size);
                }
                else
                    insert(n, current->node_get_right(),size);

            else if (current->node_get_data() > n->node_get_data())
                if (current->node_get_left() == NULL)
                {
                    current->node_set_left(n);
                    current->node_get_left()->node_set_parent(current);
                    ++c;
                    insert(n + 1, root,size);
                }
                else
                    insert(n, current->node_get_left(),size);
        }
        return n;
    }



    void print() {
        printo(root);
    }

    void printo(Node* current) {
        if (current != NULL)
        {
            printo(current->node_get_left());
            cout << current->node_get_data()<<"\t";
            printo(current->node_get_right());
        }
       

    }

};



int main()
{
    Node n(7);
    Node n1(8);
    Node n2(10);
    Node n3(6);
    Node n4(5);
    Node n5(11);
    Node arr[5] = { n,n1,n2,n3,n4 };
   
    tree tr(arr,sizeof(arr)/sizeof(Node));
    tr.add_elem(n5);
    tr.print();

}

Ответы

▲ 1Принят

В

Node* add_elem(Node n) {
  insert(n, root);
  ..
Node insert(Node n,Node* current){
  if (root == NULL)
    root = &n;
  ..

вы устанавливаете адрес локальной переменной n в root. И это адрес потом указывает в никуда. Наверное надо создавать Node в свободной памяти new Node .. и передавать указатель а не копию.

Временным исправлением будет изменение аргументов на указатели :

Node* add_elem(Node * const np) {
  insert(np, root);
  return root;
}
Node * insert(Node * const np,Node* current){
  ..

везде вместо локального объекта n нужно использовать указатель np.
И правильным решением будет создавать Node в свободной памяти :

main :

Node * n5p = new Node(11);
tr.add_elem(n5p);