/* * binary_tree.cpp * * Created on: 28.11.2013 * Author: trifon */ #ifndef __BINARY_TREE #define __BINARY_TREE #include #include #include "tree.h" using namespace std; template class BinaryTree; template struct node { node(T const& _inf, node* _left = NULL, node* _right = NULL) : inf(_inf), left(_left), right(_right) {} T inf; node *left, *right; }; template class BinaryTreeIterator { friend class BinaryTree; private: node* p; public: BinaryTreeIterator(node* _p = NULL) : p(_p) {} BinaryTreeIterator(BinaryTreeIterator const& bti) : p(bti.p) {} // it++; // преместване надясно, копие BinaryTreeIterator operator++(int) { if (p != NULL) return BinaryTreeIterator(p->right); return *this; } // ++it; // преместване наляво, копие BinaryTreeIterator operator++() { if (p != NULL) return BinaryTreeIterator(p->left); return *this; } // if (it) { ... } else { ... } // проверка за валидност operator bool() const { return p != NULL; } // cout << l.getElementAt(it); // cout << *it; // *it = 3; // получаване и установяване на стойност през итератор T& operator*() const { return p->inf; } // сравняване на итератори bool operator==(TreeIterator const& it) const { BinaryTreeIterator const& btit = (BinaryTreeIterator const&)it; return p == btit.p; } }; template class BinaryTree : public Tree > { protected: node *rootNode; void deleteNode(node *n) { if (n != NULL) { deleteNode(n->left); deleteNode(n->right); delete n; } } node* copyNode(node *n) { if (n == NULL) return NULL; return new node(n->inf, copyNode(n->left), copyNode(n->right)); } ostream& printNode(ostream& os, node* n) const { if (n == NULL) { os << '#'; return os; } os << '(' << n->inf << ' '; printNode(os, n->left) << ' '; return printNode(os, n->right) << ')'; } void adopt(node *& originalPointer, node *& newPointer) { newPointer = originalPointer; originalPointer = NULL; } void adoptLeft(node *&child) { adopt(child, rootNode->left); } void adoptRight(node *&child) { adopt(child, rootNode->right); } public: typedef BinaryTreeIterator I; BinaryTree() : rootNode(NULL) {} BinaryTree(T const& x) : rootNode(new node(x)) {} BinaryTree(T const& x, BinaryTree& l, BinaryTree& r) { rootNode = new node(x); adoptLeft(l.rootNode); adoptRight(r.rootNode); } BinaryTree(BinaryTree const& bt) { rootNode = copyNode(bt.rootNode); } BinaryTree& operator=(BinaryTree const& bt) { if (&bt != this) { deleteNode(rootNode); rootNode = copyNode(bt.rootNode); } return *this; } ~BinaryTree() { deleteNode(rootNode); } ostream& print(ostream& os) const { return printNode(os, rootNode); } T root() const { if (rootNode == NULL) return T(); return rootNode->inf; } I iterator() const { return I(rootNode); } }; template ostream& operator<<(ostream& os, BinaryTree const& bt) { return bt.print(os); } #endif