BST/Pointer in function call problem

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
#include<iostream>
using namespace std;

class btree
{
      public:
             struct node
             {
                    int data;
                    node *left;
                    node *right;
             };
             
             node *root;
             btree();
             void insert(node*,int);
             void inorder(node*);
             void preorder(node*);
             void postorder(node*);
             node* find(node*,int);
};

btree::btree()
{
              root=NULL;
}

btree::node* btree::find(node* temp,int item)
{
             if(temp==NULL)
             return temp;
             
             else if(item>temp->data)
             return find(temp->right,item);
             
             else if(item<temp->data)
             return find(temp->left,item);
             
             else return temp;
}

void btree::insert(node *temp,int item)
{
     node* place=find(temp,item);
     
     if(place==NULL)
     {
             temp=new node;
             temp->data=item;
             temp->left=NULL;
             temp->right=NULL;
                             
     }
     
     else if(item<place->data)
     insert(place->left,item);
     
     else if(item>place->data)
     insert(place->right,item);
     
}

void btree::inorder(node* temp)
{
     if(temp!=NULL)
     {
                   inorder(temp->left);
                   cout<<temp->data<<" ";
                   inorder(temp->right);
     }
}

int main()
{
    btree a;
    
    a.insert(a.root,5);
a.insert(a.root,1);
a.insert(a.root,4);
a.insert(a.root,2);
a.insert(a.root,7);
a.insert(a.root,6);
a.insert(a.root,3);
    a.inorder(a.root);
    
    system("pause");
    return 0;
}


I am not getting in output for the above code. Where am I going wrong?
Last edited on
It's your insert function, see my comments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void btree::insert(node *&temp,int item)//<--add refference, you need to work on the pointer, not a copy
{
	//node* place=find(temp,item);//<--this isn't needed

	if(temp==NULL)//<--change all place to temp
	{
		temp=new node;
		temp->data=item;
		temp->left=NULL;
		temp->right=NULL;

	}

	else if(item<temp->data)
		insert(temp->left,item);

	else if(item>temp->data)
		insert(temp->right,item);

}
Last edited on
Topic archived. No new replies allowed.