数据结构实验之求二叉树后序遍历和层次遍历【由前序序列和中序序列求后序序列,二叉树的层次遍历】

 

数据结构实验之求二叉树后序遍历和层次遍历

Time Limit: 1000MS Memory limit: 65536K

题目描述

 已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历。

输入

 输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

输出

每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列

示例输入

2
abdegcf
dbgeafc
xnliu
lnixu

示例输出

dgebfca
abcdefg
linux
xnuli
 1 #include<iostream>
 2 #include<string.h>
 3 #include<stdio.h>
 4 #include<algorithm>
 5 #include<stdlib.h>
 6 #include<queue>
 7 using namespace std;
 8 typedef struct vode
 9 {
10     char date;
11     struct vode *l,*r;
12 }bitree;
13 bitree *getpreordertraverse(char *pre,char *in,int len)
14 {
15     if(len<=0)return NULL;
16     else 
17     {
18         int k;
19         bitree *root;
20         root=(bitree *)malloc(sizeof(bitree));
21         root->date=*pre;
22         char *p;
23         for(p=in;p!=NULL;p++)
24             if(*p==*pre)break;
25         k=p-in;
26         root->l=getpreordertraverse(pre+1,in,k);
27         root->r=getpreordertraverse(pre+1+k,in+k+1,len-k-1);
28         return root;
29     }
30 }
31 void postordertraverse(bitree *root)
32 {
33     if(root)
34     {
35         postordertraverse(root->l);
36         postordertraverse(root->r);
37         cout<<root->date;
38     }
39 }
40 void cengcibianli(bitree *root)
41 {
42     queue<bitree *>s;
43     s.push(root);
44     while(!s.empty())
45     {
46         cout<<s.front()->date;
47         if(s.front()->l)
48             s.push(s.front()->l);
49         if(s.front()->r)
50             s.push(s.front()->r);
51         s.pop();
52     }
53 }
54 int main()
55 {
56      int zong;
57      while(cin>>zong)
58      while(zong--)
59      {
60          char pre[1000],in[1000];
61          cin>>pre>>in;
62          int len=strlen(in);
63          bitree *root;
64          root=getpreordertraverse(pre,in,len);
65          postordertraverse(root);
66          cout<<endl;
67          cengcibianli(root);
68          cout<<endl;
69      }
70      return 0;
71 }
View Code

 

posted @ 2013-08-03 21:11  狂盗一枝梅  阅读(739)  评论(0编辑  收藏  举报