class BinSTree { // Fields private: Node *rootNode; private: Node *currentNode; private: int errorFlag;
// default Constructor and public methods public: BinSTree(void); // insert ElementType to tree. public: void insert(ElementType); // remove ElementType. public: void remove(ValueType); // get currentNode element. public: ElementType retrieve(void); // traverse the ree, public: void traverse(int order); // find a node by value. public: void find(ValueType); // destroy tree. public: void destroy(void); // check if the tree is full. public: int isFull(void); // check if the ree empty. public: int isEmpty(void); public: int hasError(void);
void BinSTree::insert(ElementType el) { if (rootNode == 0) rootNode = new Node(el); else { Node *p = findNodeByValue(el); // if element not found before if (p == 0) { // In case root node is parent. Node *parent = rootNode; if (p != rootNode) parent = findParentForNode(el); if (el > parent->data) { parent->right = new Node(el); currentNode = parent->right; } else { parent->left = new Node(el); currentNode = parent->left; } // everthing is ok . errorFlag = false; }
Node* BinSTree::findParentForNode(ValueType key) { Node *p = rootNode, *q = 0; while ((p != 0) && (p->data != key)) { q = p; if (p->data > key) p = p->left; else p = p->right; } return q; }
Node* BinSTree::findNodeByValue(ValueType key) /* This function returns a pointer to the node containing the key value 'key' if it is in the tree. Otherwise, it returns null */ { Node *p = rootNode; while ((p != 0) && (p->data != key)) if (p->data > key) p = p->left; else p = p->right; return p; }