#ifndef __BST_H__ #define __BST_H__ #include // This typedef is meant to abstract away the idea of what // the element type is of the BST. Ideally, you would implement // a generic BST using templates, but this works in a pinch. typedef int Element; // The node structure. A BST will be built out of pointers to Nodes. struct Node { Element data; Node *left; Node *right; Node( Element d ); Node( Element d, Node *l, Node *r ); }; // The abstract base class for traversal algorithms. class TraversalFunction { public: virtual void visit( Node *cur ) = 0; }; // Printing is a generally useful operation, so it's left here // for clients to use. class Printer : public TraversalFunction { public: Printer( ostream& o ) : os( o ) {} virtual void visit( Node * node ); private: ostream& os; }; class BinarySearchTree { public: // The first four methods implement canonical form. BinarySearchTree(); BinarySearchTree( const BinarySearchTree& other ); ~BinarySearchTree(); BinarySearchTree& operator =( const BinarySearchTree& other ); int getSize(); void insert( Element item ); void remove( Element item ); bool isInTree( Element item ); void preorder( TraversalFunction& func ); void inorder( TraversalFunction& func ); void postorder( TraversalFunction& func ); void print( ostream& os ); void printNice( ostream& os ); private: // Private helper methods Node *copyFrom( Node *node ); Node *insertFrom( Node *cur, Element item ); Node *removeFrom( Node *cur, Element item ); Element minFrom( Node *cur ); bool isInTreeFrom( Node *cur, Element item ); void preorderFrom( TraversalFunction& func, Node * ); void inorderFrom( TraversalFunction& func, Node * ); void postorderFrom( TraversalFunction& func, Node * ); void printNiceFrom( int offs[], int sz, ostream& os, Node *cur, bool ir ); private: // Private data members Node *root; int size; }; #endif // __BST_H__