#ifndef GTREE_H #define GTREE_H #include #include #include using namespace std; template class gTree; template class gTNode{ public: gTNode(E data, gTNode* parent):data_(data),parent_(parent){} E getData(){ return data_;} gTNode* getParent(){return parent_;}; std::vector*> & getChildren() {return children_;} void addChild(E data){ gTNode* c= new gTNode(data, this); children_.push_back(c); } ~gTNode(){ for (int i=0; i< children_.size(); i++){ delete children_[i]; children_[i]=NULL; } } bool remove(){ if ((parent_==NULL) && (children_.size()>0)){ cout << "can't remove the root if it has children\n"; return false; } else{ parent_->children_.erase(std::remove(parent_->children_.begin(), parent_->children_.end(), this), parent_->children_.end()); for (int i=children_.size()-1;i>=0; i--){ children_[i]->parent_ = parent_; parent_->children_.push_back(children_[i]); children_[i]=NULL; children_.pop_back(); } delete this; return true; } } friend class gTree; private: E data_; gTNode* parent_; std::vector*> children_; }; template class gTree{ public: gTree():root_(NULL){} bool addNode(E itm, gTNode* parent){ if (parent == NULL){ if (root_ == NULL) root_ = new gTNode(itm, NULL); else{ cout << "Tree already has a root. " << itm << " was not added. \n"; return false; } } else { parent->addChild(itm); } return true; } gTNode* getRoot(){ return root_; } bool isEmpty(){ return root_==NULL; } ~gTree(){ delete root_; } private: gTNode* root_; }; template gTNode* findItem(gTNode* v, E itm){ if (v==NULL) return NULL; if (v->getData()==itm) return v; gTNode* result_sofar = NULL; vector*> ch = v->getChildren(); // list of children for (int i=0; i < ch.size(); i++){ result_sofar = findItem(ch[i], itm); if (result_sofar != NULL) return result_sofar; } return result_sofar; } template void preorderPrint(gTNode* v) { if (v==NULL) return; cout << v->getData(); // print element vector*> ch = v->getChildren(); // list of children for (int i=0; i < ch.size(); i++) { cout << " "; preorderPrint(ch[i]); } } template void postorderPrint(gTNode* v) { if (v==NULL) return; vector*> ch = v->getChildren(); // list of children for (int i=0; i < ch.size(); i++) { postorderPrint(ch[i]); cout << " "; } cout << v->getData(); // print element } template int size(gTNode* v) { if (v==NULL) return 0; int s = 1; vector*> ch = v->getChildren(); // list of children for (int i=0; i < ch.size(); i++) s+= size(ch[i]); return s; } #endif