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个点若为线性右子树,则需要2^30大小的数组存放二叉树,不合算;
测试数据没有那么极端,数组开10001大小即可过;
关键点
(root -(end - i + 1)) 后序root地址 - (中序右子树长度),得到下一次的左子树的后序root地址
【后序遍历根结点的位置,中序遍历的头,尾,层序遍历的索引】
头尾用于判断结束递归的条件;
根节点由前一个根节点减去中序遍历右边的子树个数得到;
void dfs(int root, int st, int ed, int index) //将root放到index中,然后找到左右子root
{
if(st > ed) return;
Level[index] = post[root];
int i=Find(In,post[root]);
dfs(root - 1 - ed + i, st, i - 1, 2*index + 1);
dfs(root - 1, i + 1, ed, 2*index + 2);
}
将post中下标为root的数放入level中下标为index的位置,st于ed为root左右子树的范围;
再将左子树放入特定index,右子树放入确定的index中;
i 的左子树下标为2i+1,右子树下标为2i+2; (i从0开始存放);
#include<iostream>
#include<vector>
using namespace std;
const int maxn=10001;
vector<int> post;
vector<int> In;
vector<int> Level;
int N;
void input(){
cin>>N;
post.resize(N);
In.resize(N);
Level.resize(maxn,-1);
for(int i=0;i<N;i++) cin>>post[i];
for(int i=0;i<N;i++) cin>>In[i];
}
int Find(vector<int> t,int n)
{
for(int i=0;i<t.size();i++)
if(t[i]==n)
return i;
}
void dfs(int root, int st, int ed, int index) //将root放到index中,然后找到左右子root
{
if(st > ed) return;
Level[index] = post[root];
int i=Find(In,post[root]);
dfs(root - 1 - ed + i, st, i - 1, 2*index + 1);
dfs(root - 1, i + 1, ed, 2*index + 2);
}
int main()
{
input();
dfs(N-1,0,N-1,0);
cout<<Level[0];
for(int i=1;i<maxn;i++)
if(Level[i]!=-1)
cout<<" "<<Level[i];
}