/////////////////////////////////////////////////////////// // MT2Q1.h // - Here, instead of graph class, used simpler // node class to illustrate idea #include template class node; template struct IFunc { typedef void(IFunc::*callback)(typename node* pNode); virtual void nodeOp(node* pNode) = 0; // pointer to node callback handler virtual void edgeOp(node* pNode) = 0; // pointer to child callback handler virtual void operator()(node* pNode, int level)=0; }; template class node { public: node(size_t number, T t=0) : nodeNum_(number), value_(t), visited_(false), pFunc_(0) {} ~node() { // Can't delete children unless you are sure they were created on heap // for(size_t i=0; i* pNode) { children_.push_back(pNode); } bool& visited() { return visited_; } size_t size() { return children_.size(); } node* getNextUnmarkedChild() { for(size_t i=0; ivisited()) return children_[i]; return 0; } void doNodeOp() { if(pFunc_) pFunc_->nodeOp(this); } void doEdgeOp() { if(pFunc_) pFunc_->edgeOp(this); } void Register(IFunc* pFunc) { pFunc_ = pFunc; } private: size_t nodeNum_; T value_; std::vector children_; bool visited_; IFunc* pFunc_; }; template void DFS(node* pNode, IFunc& f) { static int lev = 1; pNode->visited() = true; pNode->doNodeOp(); f(pNode, lev++); for(size_t i=0; isize(); ++i) { node* pChild = pNode->getNextUnmarkedChild(); if(pChild) { pChild->doEdgeOp(); DFS(pChild,f); } } --lev; }