1 #include <cstdlib>
2 #include <iostream>
3 #include <queue>
4 #define TREE_NODE_NUM 100
5
6 using namespace std;
7 typedef struct node {
8 char data;
9 struct node *lchild,*rchild;
10 }treenode;
11
12 void Creat_tree(treenode *&bt,char post[],int post_l,int post_h,char in[],int in_l,int in_h)//
13 {int i;
14 for(i=in_l;i<=in_h;i++)
15 if(in[i]==post[post_h])
16 break;
17 if(i>in_h)
18 {cout<<"输入序列错误,不能构成二叉树\n";exit(1);}
19 bt->data=post[post_h];
20 if(i==in_l)
21 {bt->lchild=NULL;}
22 else
23 {treenode *p=(treenode *)malloc(sizeof(treenode));
24 bt->lchild=p;
25
26 Creat_tree(p,post,post_l,post_l+i-1-in_l,in,in_l,i-1);//
27 }
28 if(i==in_h)
29 {bt->rchild=NULL;}
30 else
31 {treenode *p=(treenode *)malloc(sizeof(treenode));
32 bt->rchild=p;
33 Creat_tree(p,post,post_l+i-in_l,post_h-1,in,i+1,in_h);//
34 }
35 }
36
37 void C_order(treenode *bt)
38 {if(bt==NULL)
39 {cout<<"空树\n";return ;}
40 cout<<bt->data;
41 queue<treenode *> q;
42 q.push(bt);
43 treenode *p;
44 while(!q.empty())
45 {p=q.front();
46 q.pop();
47 if(p->lchild)
48 {cout<<p->lchild->data;
49 q.push(p->lchild);}
50 if(p->rchild)
51 {cout<<p->rchild->data;
52 q.push(p->rchild);}
53 }
54 }
55 void Preorder(treenode *bt)
56 {
57 if(!bt)
58 return ;
59 cout<<bt->data;
60 Preorder(bt->lchild);
61 Preorder(bt->rchild);
62 }
63
64
65
66
67 int main(int argc, char *argv[])
68 {cout<<"请输入后序遍历序列\n";
69 int i;
70 char post[TREE_NODE_NUM];
71 int post_l,post_h;
72 gets(post);
73 for(i=0;post[i];i++);
74 post_l=0;post_h=i-1;
75 cout<<"请输入中序遍历序列\n";
76 char in[TREE_NODE_NUM];
77 int in_l,in_h;
78 gets(in);
79 in_l=0;in_h=i-1;
80 if(in_l>in_h)
81 {cout<<"数为空树\n";return 1;}
82
83
84 treenode *bt=(treenode *)malloc(sizeof(treenode));
85 Creat_tree(bt,post,post_l,post_h,in,in_l,in_h);
86 cout<<"层次遍历:";
87 C_order(bt);
88 cout<<endl;
89 cout<<"先序遍历: ";
90 Preorder(bt);
91 cout<<endl;
92
93
94
95
96
97 system("PAUSE");
98 return EXIT_SUCCESS;
99 }
100
101