/* * bintree.cpp * * Created on: 5.01.2015 г. * Author: trifon */ #ifndef __BINTREE_CPP #define __BINTREE_CPP #include using namespace std; template struct TreeNode { TreeNode(T const& _data = T(), TreeNode* _left = NULL, TreeNode* _right = NULL) : data(_data), left(_left), right(_right) {} T data; TreeNode *left, *right; }; template class BinaryTreeIterator { // BinaryTree t; // BinaryTreeIterator it = t.iterator(); // cout << *it; // *it = 5; // it++ --> връщат итератора на дясното поддърво // ++it --> връщат итератора на лявото поддърво // if (it) ... // if (!it) ... private: TreeNode* ptr; static T error; public: BinaryTreeIterator(TreeNode* _ptr = NULL) : ptr(_ptr) {} T& operator*() { if (ptr == NULL) return error; return ptr->data; } // ++it BinaryTreeIterator operator++() const { if (ptr == NULL) return *this; return BinaryTreeIterator(ptr->left); } // it++ BinaryTreeIterator operator++(int) const { if (ptr == NULL) return *this; return BinaryTreeIterator(ptr->right); } operator bool() const { return ptr != NULL; } }; template T BinaryTreeIterator::error; template class BinaryTree { protected: TreeNode* root; private: void deleteNode(TreeNode* node) { if (node != NULL) { deleteNode(node->left); deleteNode(node->right); delete node; } } TreeNode* copyNode(TreeNode* src) { if (src == NULL) return NULL; return new TreeNode(src->data, copyNode(src->left), copyNode(src->right)); } void adoptLeft(TreeNode*& node) { adopt(root->left, node); } void adoptRight(TreeNode*& node) { adopt(root->right, node); } void adopt(TreeNode*& newNode, TreeNode*& oldNode) { newNode = oldNode; oldNode = NULL; } public: BinaryTree() : root(NULL) {} BinaryTree(T const& data) : root(new TreeNode(data)) {} BinaryTree(T const& data, BinaryTree& left, BinaryTree& right) { root = new TreeNode(data); adoptLeft(left.root); adoptRight(right.root); } BinaryTree(BinaryTree const& bt) { root = copyNode(bt.root); } BinaryTree& operator=(BinaryTree const& bt) { if (this != &bt) { deleteNode(root); root = copyNode(bt.root); } return *this; } ~BinaryTree() { deleteNode(root); } // !!!TreeNode* getRoot() const { return root; } typedef BinaryTreeIterator I; I iterator() const { return I(root); } }; template ostream& operator<<(ostream& os, BinaryTree const& bt) { return os << bt.iterator(); } template ostream& operator<<(ostream& os, BinaryTreeIterator it) { if (!it) return os; return os << '(' << *it << ',' << ++it << ',' << it++ << ')'; } #endif