#ifndef __BS_TREE_HPP__ #define __BS_TREE_HPP__ #include template class btree { private: T data; bool empty; // indicate if the tree is empty btree* left, * right; public: btree() { left = right = NULL; empty = true;} btree(const T& x) { data = x; empty = false; left = right = NULL; } btree(const btree* tree2); ~btree(); bool isEmpty() { return empty; } void binsert(const T& x); bool find(const T& x) const; void inorder(std::ostream& out); void preorder(std::ostream& out); void postorder(std::ostream& out); }; // copy constructor template btree::btree(const btree* tree2):btree() { if (tree2 == NULL) return; data = tree2->data; empty = tree2->empty; if (tree2->left != NULL) { left = new btree(tree2->left); } if (tree2->right != NULL) { right = new btree < T(tree2->right); } } // destructor template btree::~btree() { if (left != NULL) delete left; if (right != NULL) delete right; } template void btree::binsert(const T& x) { // if the tree is empty if (empty) { data = x; empty = false; } else { // insertion into the left subtree if (x <= data) { // left subtree is empty if (left == NULL) { left = new btree(x); } else { left->binsert(x); } } else { // insertion into the right subtree // right subtree is empty if (right == NULL) { right = new btree(x); } else { right->binsert(x); } } } } template bool btree::find(const T& x) const { if (empty) return false; if (data == x) return true; if (x <= data) { if (left == NULL) return false; else return left->find(x); } else { // x might be stored in right subtree if (right == NULL) return false; else return right->find(x); } } template void btree::inorder(std::ostream& out) { if (empty) return; if (left != NULL) { left->inorder(out); } out << " " << data; if (right != NULL) { right->inorder(out); } } template void btree::preorder(std::ostream& out) { if (empty) return; out << " " << data; if (left != NULL) { left->preorder(out); } if (right != NULL) { right->preorder(out); } } template void btree::postorder(std::ostream& out) { if (empty) return; if (left != NULL) { left->postorder(out); } if (right != NULL) { right->postorder(out); } out << " " << data; } #endif