c++ simple trees

Can someone please tell me why the code crashes? I'm trying to code a simple binary search tree.

Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "tree.h"


int main()
{

Tree one;

one.add_node(15);
one.add_node(66);
one.add_node(22);

one.find_value(66);

    return 0;
}


Tree.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef TREE_H
#define TREE_H


struct node{

    int data;
    node *left;
    node *right;
};

class Tree
{
    node *root;

    public:
        Tree();
        void add_node(int data);
        void find_value(int search_data);

};

#endif // TREE_H 



Tree.cpp

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
#include "Tree.h"
#include <iostream>
Tree::Tree()
{
    root->left=NULL;
    root->right=NULL;
}

void Tree::add_node(int value){

    node *temp = root;
    node *last_node = new node;
    while(temp!=NULL){

        last_node = temp;

        if(value>=temp->data)
            temp=temp->right;
        else
            temp=temp->left;
    }
    node *new_node = new node;

    if(value>=last_node->data){
        last_node->right=new_node;
        last_node->right->data=value;
    }
     else{
        last_node->left=new_node;
        last_node->left->data=value;
     }

}

void Tree::find_value(int search_data){

    node *temp = root;
    while(temp!=NULL){

        if(temp->data==search_data){break;}
        if(temp->data<=search_data){temp=temp->right;}
        else{temp=temp->left;}
    }

    if(temp->data==search_data){std::cout<<search_data;}
    else{std::cout<<"NOT FOUND";}
}




Last edited on
1
2
3
class Tree
{
    node *root;


1
2
3
4
5
6
Tree::Tree()
{
  // Which node object does the root point to right now?
    root->left=NULL;
    root->right=NULL;
}
Thanks for the help
Topic archived. No new replies allowed.