P1030 求先序排列 - 分治

https://www.luogu.org/problemnew/show/1030

题目描述

给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。

输入输出格式

输入格式:

2行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。

输出格式:

1行,表示一棵二叉树的先序。

输入输出样例

输入样例#1: 
BADC
BDCA
输出样例#1: 
ABCD
 1 #include<cstdio>
 2 #include<string>
 3 #include<iostream>
 4 using namespace std;
 5 string mx,hx;
 6 void dfs(string mx,string hx)
 7 //例 中序ACGDBHZKX 后序CDGAHXKZB 
 8 {
 9     if(hx.size()>0)
10     {
11         char k=hx[hx.size()-1];//后序遍历的最后一个是根 此处为B 
12         cout<<k;//求先序遍历 先输出根 
13         int mid=mx.find(k);//在中序遍历中找到根,从根处把中序遍历的字符串分为左右子树 
14         dfs(mx.substr(0,mid),hx.substr(0,mid));
15         //左子树 对应中序 ACGD 后序 CDGA
16         dfs(mx.substr(mid+1),hx.substr(mid,hx.size()-mid-1));
17         //右子树 对应中序 HZKX 后序 HXKZ
18         //递归求解 
19     }
20     
21 }
22 int main()
23 {
24     cin>>mx;
25     cin>>hx;
26     dfs(mx,hx);
27     return 0;
28 }

 P.S

①已知中序与后序,求先序↑

②已知先序与中序,求后序

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 string fx,mx;
 6 void dfs(string fx,string mx)
 7 //例 先序 abdec 中序 dbeac 
 8 {
 9     if(mx.size()>0)
10     {
11         char root=fx[0];//先序排列的第一个元素是根 此处为a 
12         int k=mx.find(root);//在中序遍历中找到根 
13         dfs(fx.substr(1,k),mx.substr(0,k));
14         //左子树 中序 dbe 对应 先序 bde 
15         dfs(fx.substr(k+1),mx.substr(k+1,mx.size()-k-1));
16         //右子树 中序 c 对应 先序 c 
17         cout<<root;//求后序遍历 最后输出根节点 
18     }
19 }
20 int main()
21 {
22     cin>>fx;
23     cin>>mx;
24     dfs(fx,mx);
25     return 0;
26 }

 

posted @ 2018-01-06 09:00  dprswdr  阅读(287)  评论(0编辑  收藏  举报