1 #include "iostream"
2 using namespace std;
3
4 typedef char type;
5 struct bnode{
6 type data;
7 bnode *lchild,*rchild;
8 };
9
10 class tree{
11 public:
12 tree();//初始化
13 ~tree();
14 void create_tree(bnode *&T);//建立二叉树
15 void preorder(bnode *T);//先序遍历
16 void inorder(bnode *T);//中序遍历
17 void postorder(bnode *T);//后序遍历
18 private:
19 int count;//元素个数统计
20 };
21
22 tree::tree()//初始化
23 {
24 count = 0;
25 }
26
27 void tree::create_tree(bnode *&T)//建立二叉树
28 {
29 type x;
30 cin>>x;
31 if(x=='.')T=NULL;
32 else {
33 T = new bnode;
34 T->data = x;
35 count++;
36 create_tree(T->lchild);
37 create_tree(T->rchild);
38 }
39 }
40
41 void tree::preorder(bnode*T)//先序遍历
42 {
43 if(T!=NULL)
44 {
45 cout<<T->data<<" ";
46 preorder(T->lchild);
47 preorder(T->rchild);
48 }
49 }
50
51 void tree::inorder(bnode*T)//中序遍历
52 {
53 if(T!=NULL)
54 {
55 inorder(T->lchild);
56 cout<<T->data<<" ";
57 inorder(T->rchild);
58 }
59 }
60
61 void tree::postorder(bnode*T)//后序遍历
62 {
63 if(T!=NULL)
64 {
65 postorder(T->lchild);
66 postorder(T->rchild);
67 cout<<T->data<<" ";
68 }
69 }
70
71 tree::~tree(){}
72
73 int main()
74 {
75 tree Tree;
76 bnode *T;
77 cout<<"Create Tree:";
78 Tree.create_tree(T);
79 cout<<"Tree finished!"<<endl;
80 cout<<"preorder Tree:";
81 Tree.preorder(T);
82 cout<<endl;
83 cout<<"inorder Tree:";
84 Tree.inorder(T);
85 cout<<endl;
86 cout<<"postorder Tree:";
87 Tree.postorder(T);
88 cout<<endl;
89 return 0;
90 }