/* * tree.cpp * * Created on: 28.11.2012 * Author: trifon */ #ifndef __TREE_CPP #define __TREE_CPP #include #include "tree.h" using namespace std; template struct node { T inf; node *left, *right; }; template class BinTree; template class BinTreeIterator : public TreeIterator { private: node* p; public: BinTreeIterator(node* _p = NULL) : p(_p) {} BinTreeIterator operator++() const { return BinTreeIterator(p->left); } BinTreeIterator operator++(int) const { return BinTreeIterator(p->right); } T& operator*() const { return p->inf; } operator bool() const { return p != NULL; } bool operator==(TreeIterator const& it) const { BinTreeIterator const& btit = (BinTreeIterator const&)it; return p == btit.p; } }; template class BinTree : public Tree > { protected: node* root; void adopt(node*& dest, node*& src) { dest = src; src = NULL; } void deleteNode(node* n) { if (n != NULL) { deleteNode(n->left); deleteNode(n->right); delete n; } } void copyNode(node*& dest, node const * src) { if (src == NULL) dest = NULL; else { dest = new node; dest->inf = src->inf; copyNode(dest->left, src->left); copyNode(dest->right, src->right); } } public: BinTree() : root(NULL) {} BinTree(BinTree const& bt) { copyNode(root, bt.root); } BinTree& operator=(BinTree const& bt) { if (&bt != this) { deleteNode(root); copyNode(root, bt.root); } return *this; } ~BinTree() { deleteNode(root); } bool empty() const { return root == NULL; } typedef BinTreeIterator I; I iterator() const { return I(root); } void adoptLeft(BinTree& t) { if (root != NULL) adopt(root->left, t.root); } void adoptRight(BinTree& t) { if (root != NULL) adopt(root->right, t.root); } void createTree(T const& inf, BinTree& ltree, BinTree& rtree) { deleteNode(root); root = new node; root->inf = inf; adoptLeft(ltree); adoptRight(rtree); } bool rootTree(T& inf) const { if (root == NULL) return false; inf = root->inf; return true; } void print() const { print(iterator()); } void print(I it) const { if (!it) return; cout << '(' << *it << ','; print(++it); cout << ','; print(it++); cout << ")"; } }; #endif