gentree.h
Go to the documentation of this file.00001 #ifndef GENTREE_H
00002 #define GENTREE_H
00003
00004
00005
00006
00007 #include <queue>
00008
00009 using namespace std;
00010
00011
00012
00016 template<class T> struct node {
00017
00018 node() : data(), child(0), sibling(0), parent(this) {}
00019
00020 node(const T& val) : child(0), sibling(0), parent(this) { data=val; }
00021
00022 node(const T& val, node<T> *p) : child(0), sibling(0) { data=val; parent=p; }
00023
00024
00025
00026
00027
00028 void add_child(const T& chi) { child = new node<T>(chi, this); }
00029 void add_sibling(const T& sib) { sibling = new node<T>(sib, this->parent); }
00030 void setData(const T& d) { data = d; }
00031 node<T>* right() { return sibling; }
00032 node<T>* down() { return child; }
00033 vector<T> row();
00034 vector<T> col();
00035
00036 T data;
00037 node<T> *child;
00038 node<T> *sibling;
00039 node<T> *parent;
00040 };
00041
00042
00043 template<class T> vector<T> node<T>::row() {
00044 node<T>* ptr = sibling;
00045 vector<T> tmp;
00046 while (ptr) {
00047 tmp.push_back(ptr->data);
00048 ptr = ptr->sibling;
00049 }
00050 return tmp;
00051 }
00052
00053 template <class T> vector<T> node<T>::col() {
00054 node<T>* ptr = sibling;
00055 vector<T> tmp;
00056 while (ptr) {
00057 tmp.push_back(ptr->data);
00058 ptr = ptr->child;
00059 }
00060 return tmp;
00061 }
00062
00063
00064 template<class T> void preorder(node<T> *n, void (*vis)(node<T>*)) {
00065 if (n) {
00066 vis(n);
00067
00068 preorder(n->child, vis);
00069 preorder(n->sibling, vis);
00070 }
00071 else {
00072 vis(0);
00073 }
00074 }
00075
00076
00077
00078
00079 template<class T> void levelorder(node<T> *n, void (*vis)(node<T>*)) {
00080 queue<node<T>* > nodes_left;
00081 nodes_left.push(n);
00082 node<T>* p;
00083
00084 while (!nodes_left.empty()) {
00085 p = nodes_left.front();
00086
00087 while (p) {
00088 vis(p);
00089 if (p->child) nodes_left.push(p->child);
00090 p = p->sibling;
00091 }
00092 vis(0);
00093 nodes_left.pop();
00094 }
00095 }
00096
00097
00098 template<class T> void postorder(node<T> *n, void (*vis)(node<T>*)) {
00099 if (n) {
00100 postorder(n->child, vis);
00101 postorder(n->sibling, vis);
00102 vis(n);
00103 }
00104 else {
00105 vis(0);
00106 }
00107 }
00108
00109
00110
00111 template<class T> void deltree(node<T> *n) {
00112 if (n) {
00113 deltree(n->child);
00114 deltree(n->sibling);
00115
00116 delete n;
00117 }
00118 }
00119
00120 #endif