BST.hpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <stack>
using namespace std;
template<class T>
class Node
{
public:
T data;
Node* left;
Node* right;
Node(T e) {
this->data = e;
this->left = NULL;
this->right = NULL;
}
};
template<class T>
class BST {
public:
BST() {
root = NULL;
size = 0;
}
int Size() {
return size;
}
bool IsEmpty() {
return size == 0;
}
void add(T e) {
root = add(root, e);
}
bool Contains(T e) {
return Contains(root, e);
}
void preOrder() {
preOrder(root);
}
void preOrderNew() {
stack<Node<T>*> st = stack<Node<T>*>();
st.push(root);
while (!st.empty()) {
Node<T>* cur = st.top();
st.pop();
cout << cur->data<<endl;
if (cur->right != NULL) {
st.push(cur->right);
}
if (cur->left != NULL) {
st.push(cur->left);
}
}
}
void inOrder() {
inOrder(root);
}
void postOrder() {
postOrder(root);
}
void toString() {
GenerateBSTtoString(root, 0);
}
private:
Node<T>* add(Node<T>* node, T e) {
if (node == NULL) {
size++;
return new Node<T> (e);
}
if (e < node->data) {
node->left=add(node->left, e);
}
else if (e > node->data) {
node->right=add(node->right, e);
}
return node;
}
bool Contains(Node<T>* node, T e) {
if (node == NULL) {
return false;
}
if (e == node->data) {
return true;
}
else if (e < node->data) {
return Contains(node->left, e);
}
else {
return Contains(node->right, e);
}
}
void preOrder(Node<T>* node) {
if (node == NULL) {
return;
}
cout << node->data << ","<< endl;
preOrder(node->left);
preOrder(node->right);
}
void inOrder(Node<T>* node) {
if (node == NULL) {
return;
}
inOrder(node->left);
cout << node->data << "," << endl;
inOrder(node->right);
}
void postOrder(Node<T>* node) {
if (node == NULL) {
return;
}
postOrder(node->left);
postOrder(node->right);
cout << node->data << "," << endl;
}
void GenerateBSTtoString(Node<T>* node,int depth) {
if (node == NULL) {
GenerateDepthString(depth);
cout << "NULL" << endl;
return;
}
GenerateDepthString(depth);
cout << node->data << endl;
GenerateBSTtoString(node->left, depth + 1);
GenerateBSTtoString(node->right, depth + 1);
}
void GenerateDepthString(int depth) {
for (int i = 0; i < depth; i++) {
cout << "--";
}
}
private:
Node<T>* root;
int size;
};
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <string>
#include "BST.hpp"
using namespace std;
int main(void)
{
BST<int> bst = BST<int>();
int num[] = {5,3,6,8,4,2};
for (int i = 0; i < sizeof(num) / sizeof(int);i++){
bst.add(num[i]);
}
bst.preOrder();
cout << "__________________" << endl;
//bst.toString();
bst.preOrderNew();
cout << "__________________" << endl;
//bst.toString();
bst.inOrder();
cout << "__________________" << endl;
bst.postOrder();
cout << "__________________" << endl;
system("pause");
return 0;
}