binary tree c++

The program compiles, but when I run it, it crashes when it tries to output
what is wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
//-------------------------- Node.h
  class Node
{
public:
    Node* _RHand ;
    Node* _LHand;
    Node* _head;
    int data ;
    Node()=delete ;
    Node (int input_data);
    void insert_Node(int data , Node* Ihead = nullptr);
    void get_min();


};
//--------------------Node.cpp
#include "node.h"
#include <iostream>
using std::cout;
Node::Node(int input_data)
{
        this->data = input_data ;
        this->_head = this ;
        this->_LHand = nullptr ;
        this->_RHand = nullptr ;
}
void Node::insert_Node(int data , Node* Ihead ){

    if (Ihead == nullptr ) Ihead = this->_head ;
    if (Ihead->data >data){
        if (Ihead->_LHand == nullptr){

            Node* tem  = new Node (data) ;
            Ihead ->_LHand = tem ;
            delete tem ;
        }else{


           insert_Node(data,  Ihead->_LHand);


        }
    }else {
         if (Ihead->_RHand == nullptr){

             Node* tem  = new Node (data) ;
             Ihead ->_RHand = tem ;
             delete tem ;



         }else {

               insert_Node(data,  Ihead->_RHand);

         }
    }

}
void Node::get_min(){

    Node* tem  = _head;


    while (tem->_LHand !=nullptr) {
            cout<< tem->data ;
            tem =tem->_LHand ;
    }



}  
//------------main
  #include "node.h"


int main()
{
    Node* start  = new Node (32);
    start ->insert_Node(23);
    start ->insert_Node(15);
    start ->insert_Node(13);
    start ->insert_Node(3);
    start ->insert_Node(2);
    start->get_min();


}

You should not delete the new node after it has been added to the tree. It's still needed. You should only delete a node when you are absolutely sure it's not going to be used anymore.
Last edited on
1
2
3
   Node* tem  = new Node (data) ;
            Ihead ->_LHand = tem ;
            delete tem ;


Here it looks like you are creating a node, adding it to the tree, and then deleting the node object. So now you've got pointers in your tree pointing to bad memory. This doesn't look right at all.
thank you guys but there is another question how to avoid memory leaks in the program?
To avoid memory leaks, make sure that everything you create using new gets destroyed using delete.

Better than that, don't do dynamic memory allocation. Don't create anything with new or malloc. There's no need to in this situation.
Topic archived. No new replies allowed.