1 //一般树的手工打造,遍历,求节点数和树高
2 #include <cstdlib>
3 #include <iostream>
4 #include <vector>//使用向量需包含该文件
5
6 using namespace std;
7
8 template<typename T>
9 struct Tnode{
10
11 typedef vector<Tnode*> CT; //特别注意向量后的<数据呈放类型>,太坑了!!!
12 //typedef CT child_container_type;
13 typedef T Value_type;
14 CT children_;
15 T value_;
16 Tnode(T const& v=T()):value_(v){}
17 T& value(void){return value_;}
18 void add_child(Tnode* ch){children_.push_back(ch);}
19 int degree(void) const{return children_.size();}
20 bool leafnode(void) const{return children_.empty();}
21 };
22
23 template<typename NT>
24 int size(NT* root){
25 if(root==0) return 0;
26 int result=1;
27 typedef typename NT::CT::iterator CI;
28 CI fc=root->children_.begin();//返回容器向量的首地址
29 CI lc=root->children_.end();
30 for(;fc!=lc;++fc) result+=size(*fc);
31 return result;
32 }
33
34 template<typename NT>
35 int height(NT* root){
36 if(root==0) return 0;
37 int max=0;
38 typedef typename NT::CT::iterator CI;
39 CI fc=root->children_.begin();
40 CI lc=root->children_.end();
41 for(;fc!=lc;++fc){
42 int h=height(*fc);
43 if(h>max) max=h;
44 }
45 return max+1;
46 }
47
48 template<typename NT>
49 void preorder(NT* root,void(*visit)(NT*)){
50 if(root!=0){
51 visit(root);
52 typedef typename NT::CT::iterator CI;
53 CI fc=root->children_.begin();
54 CI lc=root->children_.end();
55 for(;fc!=lc;++fc)
56 preorder(*fc,visit);
57 }
58 }
59
60 template<typename NT>
61 void postorder(NT* root,void(*visit)(NT*)){
62 if(root!=0){
63 typedef typename NT::CT::iterator CI;
64 CI fc=root->children_.begin();
65 CI lc=root->children_.end();
66 for(;fc!=lc;++fc)
67 postorder(*fc,visit);
68 visit(root);
69 }
70 }
71
72 //template<typename NT>
73 typedef Tnode<char> NT;
74 void print(NT* p){std::cout<<p->value()<<"";}
75
76 int main(int argc, char *argv[])
77 {
78 NT e('E');NT f('F');NT b('B');
79 b.add_child(&e);b.add_child(&f);//注意怎样取模板类对象的地址
80 NT g('G');NT c('C');
81 c.add_child(&g);
82 NT d('D');NT a('A');
83 a.add_child(&b);a.add_child(&c);
84 NT* root=&a;
85 int as=size(root);
86 int ah=height(root);
87 int ad=a.degree();
88 bool al=a.leafnode(); bool dl=d.leafnode();
89 preorder(root,&print);cout<<endl;
90 postorder(root,&print);cout<<endl;
91
92 system("PAUSE");
93 return EXIT_SUCCESS;
94 }
![]()