Help with binary search tree

I want to display the numbers in a bst but all I get are 0s, what is wrong with my code that is causing 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
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
89
90
91
92
93
94
#include <iostream>
using namespace std;

class binarySearchTree
{
private:
	class TreeNode
	{
		friend class binarySearchTree;
		int value;
		TreeNode *left;
		TreeNode *right; 

		TreeNode(int value1, TreeNode *left1 = NULL, TreeNode *right1 = NULL)
		{
			int value = value1;
			left = left1;
			right = right1; 
		}

	};

	TreeNode *root;

	void insert(TreeNode *&tree, int x)
	{
		if (!tree)
		{
			tree = new TreeNode(x);
			return;
		}
		if (tree->value == x)
		{
			return;
		}
		if (x < tree->value)
		{
			insert(tree->left, x);
		}
		else
			insert(tree->right, x);
	}

	void display(TreeNode *tree)
	{
		if (tree)
		{
			cout << tree->value;
			display(tree->left);
			display(tree->right); 
		}
	}

public:
	binarySearchTree()

	{
		root = NULL;
	}
	~binarySearchTree()
	{

	}
	void insert(int num)
	{
		insert(root, num);
	}
	void displaytree(void)
	{
		display(root);
	}

};

int main()
{

	binarySearchTree bst;

	bst.insert(47);
	bst.insert(13);
	bst.insert(5);
	bst.insert(83);
	bst.insert(28);
	bst.insert(67);
	bst.insert(91);
	bst.insert(41);

	//print all items in tree to screen
	bst.displaytree();


	return 0;
}
If you add << '\n' to line 48 so each node prints on a different line, you'll see that it's printing 0 for each node. So the question is why? The answer is on line 16. You're assigning value1 to the local variable value, not the member variable value, so the member is never set. Just remove "int" from that line and it will work.

However, your display function displays the nodes in prefix order: first the current node, then left tree (all nodes less than the current one), and then the right tree. You probably want to display it in infix order the the numbers come out in sorted order.
Topic archived. No new replies allowed.