Can you review my simple Binary Search Tree?

Hello! My name is Stuart and I'm a moderate programmer who is currently trying to get his coding knowledge up to scratch. I'm also quite new to C++ hence this topic in this forum.

I've made a simple working BST which is one of my first attempts at a data structure and also the most complete thing I have written in C++ so far. I'm looking for any feedback you can give me regarding technique, code readability, anything really. Although if you could tell me whether keeping the recursive member functions that deal with pointers private is needed or not that would be great.

I want to build on this and add self-balancing so be as harsh as you like. I am here to learn. Thanks!

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
#include "../../std_lib_facilities.h"


class Node {
public:
	Node(const int& n, Node* l = 0, Node* r = 0)
		: key(n), left(l), right(r) {}

	int getKey() const { return key; }
	Node* getLChild() const {return left; }
	Node* getRChild() const { return right; }
	void setLChild(Node* np) {left = np;}
	void setRChild(Node* np) {right = np;}

private:
	int key;

	Node* left;
	Node* right;
};


class BST {
public:
	BST()
		:root(0){}

	void add(int);
	void outputTree();

private:
	void recAdd(Node*,int);   // Private recursive member functions to keep pointer manipulation away from user
	void recOutputTree(Node*);

	Node* root;
};


void BST::add(int n)
{
	if(root==0) root = new Node(n);
	else recAdd(root,n);
	
}

void BST::recAdd(Node* tempRoot, int n)
{
	if(n < tempRoot->getKey() ) {
		if( !tempRoot->getLChild() ) { tempRoot->setLChild(new Node(n)); }
		else { recAdd(tempRoot->getLChild(),n); }
	}
	else if(n > tempRoot->getKey() ) {
		if( !tempRoot->getRChild() ) { tempRoot->setRChild(new Node(n)); }
		else { recAdd(tempRoot->getRChild(),n); }
	}
}

void BST::outputTree()
{
	if (!root) cout << "NULL TREE" << endl;
	else recOutputTree(root);
}

void BST::recOutputTree(Node* tempRoot)
{
	if(tempRoot->getLChild() ) recOutputTree( tempRoot->getLChild() );
	cout << "Key: " << tempRoot->getKey() << endl;
	if(tempRoot->getRChild() ) recOutputTree( tempRoot->getRChild() );
}

int _tmain(int argc, _TCHAR* argv[])
{

	BST bst;

	for (int i=0; i < 200; i++)  // adds numbers backwards see we can see if the tree is sorting
		bst.add(200-i);


	bst.outputTree();

	keep_window_open();
	return 0;
}
Topic archived. No new replies allowed.