BST question

I am trying to print the elements of the tree but am not getting anything to print

Driver program:
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
#include "BST.h"
#include "header_file.h"

template <class T>
void print_vals(T& x) { cout << x << ' ' << "X"; } 

int main () 
{
int seed = 1;
int n;
vector<int> v;

cout << "Enter a number: ";
cin >> n;

srand(seed);
for(int i = 0; i < v.size(); i++)
v[i] = rand() % n + 1;

BST<int> t;
for(int j = 0; j < v.size(); j++)
t.insert(v[j]);

t.inOrder(print_vals);

return 0;
}

BST.H: 
#include "BT.h"

#ifndef H_BST
#define H_BST

template<class T> 
class BST : public BT<T> {

public:
void insert(const T& x) { insert(root, x); }

protected:
Node<T>* root;

private:
void insert(Node<T>*&, const T&);

};
#endif

template <class T>
void BST<T>::insert(Node<T>*& p, const T& x)
{
p = root;
Node<T> *prev = 0;

while(p != 0)
{
prev = p;
if(p->data < x)
p = p->right;
else
p = p->left;
}
if (root == 0) root = new Node<T>(x);
else if (prev->data < x);
{
prev->right = new Node<T>(x);
prev->left = new Node<T>(x); 
}
}
You have the code in two files, right?
Yes i do, i just put the together on here to make it easier to read
Oh, OK. I wasn't sure. My friend has made that exact mistake (what it looks like in your box, only all in one file) in real life.
Ok.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main () 
{
int seed = 1;
int n;
vector<int> v;

cout << "Enter a number: ";
cin >> n; // N is declared.

srand(seed);
for(int i = 0; i < v.size(); i++) // v.size is 0 so nothing happens
v[i] = rand() % n + 1;

BST<int> t; 
for(int j = 0; j < v.size(); j++) // v.size is 0 still, again nothing happens
t.insert(v[j]);

t.inOrder(print_vals); // nothing has happened, nothing to print.

return 0;
}
OK i changed it to this:
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
#include "BST.h"
#include "header_file.h"

template <class T>
void print_vals(T& x) { cout << x << " "; } 

int main () 
{
	int seed = 1;
	int n;
	
	cout << "Enter a Number: ";
	cin >> n;
	
	vector<int> v(n);
	
	srand(seed);
	for(int j = 0; j < v.size(); j++) //Now v.size() = n
		v[j] = rand() % n + 1;
	
	BST<int> t;
	for(int j = 0; j < v.size(); j++)
		t.insert(v[j]);

	t.inOrder(print_vals);
	
	return 0;
}


This is my insert method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template <class T>
void BST<T>::insert(const T& x)
{
	Node<T>* p = root;
	Node<T> *prev = 0;
	
	while(p != NULL)
	{
		prev = p;
		if(p->data < x)
			p = p->right;
		else
			p = p->left;
	}
	if(root == 0)
		root = new Node<T>(x);
	else if(prev->data < x)
		prev->right = new Node<T>(x);
	else
		prev->left = new Node<T>(x);
	
}

I am still not getting anything to print. What am i still doing wrong?
Topic archived. No new replies allowed.