**
1020 Tree Traversals (25分)
**
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
题意:题目为一棵二叉树,节点n<=30,给定后序遍历和中序遍历结果,现在要求输出水平遍历,又叫层次遍历结果,比如样例的图画出来是这样的。
那么层次遍历的结果就是4,1,6,3,5,7,2
题解:这种题目在数据结构中应该是比较常见的,不过我本人接触比较少,看到这个题目的时候是现场根据后序遍历和中序遍历的规律推导的,可能对数据结构比较熟练的同学是很简单的,这里我也分享下我的推导过程,我以这个样例进行分析。
首先记住遍历的过程:
后序遍历:先左节点再右节点最后根节点
中序遍历:先左节点再根节点最后右节点
这里遍历的顺序要求了,记住真的很重要!!!
现在开始分析
给定
step1
后序遍历结果:2 3 1 5 7 6 4
中序遍历结果:1 2 3 4 5 6 7
由后序遍历顺序可知,4为当前树结构的根节点,再由中序遍历顺序可知,1 2 3为根节点4的左子树内容,5 6 7为根节点4的右子树内容。
step1.1
于是我们将左子树内容1 2 3进行分治处理,内容为:
后序遍历结果:2 3 1
中序遍历结果:1 2 3
同理可知后序遍历结果告诉1为当前树结构的根节点,再由中序遍历顺序可知根节点1没有左子树,2 3为根节点右子树内容
step1.1.1
左子树为空,返回
step1.1.2
将右子树内容进行分治处理,内容为:
后序遍历结果:2 3
中序遍历结果:2 3
同理可知3为当前树结构根节点,由中序遍历知2为根节点3的左子树内容
。。。。。。
右子树5 6 7 的分析过程不再赘述。
于是题目解答思路很清晰了,就是不断递归处理,那么为了方便输出层次遍历结果,可以定义动态数组vectorv[50],v[dp]表示第dp层的内容,然后每次递归都有一个深度就是树的结构深度,每次让v[dp]=当前根节点,最后直接输出答案就好,解答完成。
AC代码
#include<bits/stdc++.h>
using namespace std;
vector<int>v[50];
//q1表示后序遍历结果,q2表示中序遍历结果,dp为当前树的深度
void solve(vector<int>q1,vector<int>q2,int dp)
{
//如果子树为空,返回
if(q1.size()==0)return;
//q3为左/右子树后序遍历结果
//q4为左/右子树中序遍历结果
vector<int>q3,q4;
int n=q1.size()-1;
//pos表示根节点当中序遍历结果中的位置
int pos;
for(int i=0;i<=n;i++)
{
if(q2[i]==q1[n])
{
pos=i;
break;
}
}
//按层次遍历装入数组,方便答案输出
v[dp].push_back(q1[n]);
//加载左子树后序遍历和中序遍历内容
for(int i=0;i<pos;i++)
{
q3.push_back(q1[i]);
q4.push_back(q2[i]);
}
//按照层次遍历要求先处理左子树
solve(q3,q4,dp+1);
q3.clear();
q4.clear();
//加载右子树内容
for(int i=pos;i<n;i++)
{
q3.push_back(q1[i]);
//注意在中序遍历中q2[pos]表示根节点,需要跳过,所以+1
q4.push_back(q2[i+1]);
}
//处理右子树
solve(q3,q4,dp+1);
}
int main()
{
int n;
cin>>n;
vector<int>q1,q2;
for(int i=0;i<n;i++)
{
int x;
cin>>x;
q1.push_back(x);
}
for(int i=0;i<n;i++)
{
int x;
cin>>x;
q2.push_back(x);
}
solve(q1,q2,1);
//输出答案
int ans=0;
for(int i=1;i<=30;i++)
{
for(int j=0;j<v[i].size();j++)
{
ans++;
if(ans==n)
cout<<v[i][j]<<endl;
else cout<<v[i][j]<<" ";
}
}
return 0;
}