1020 Tree Traversals (25 分)

时间:2023-11-11 13:46:26

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 (≤), 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
分析:根据后序遍历和中序遍历 输出层序遍历
我的做法是利用后序遍历和中序遍历建树 再层序遍历输出
利用两个变量来记录我们需要建子树的范围 另一个变量记录每层的根节点
 #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;
typedef struct BtNode* Bt;
struct BtNode
{
int Num;
Bt RT;
Bt LT;
};
vector<vector<int> > Order();
Bt BuildTree(Bt T,int i2,int j2,int j1)
{
if (i2 >= j2)
return T;
int i = i2;
for (; i < j2; i++)
{
if (Order[][i] == Order[][j1 - ])
break;
}
if (!T)
{
T = new BtNode();
T->LT = NULL;
T->RT = NULL;
T->Num = Order[][i];
}
T->LT =BuildTree(T->LT,i2,i,j1-j2+i);
T->RT = BuildTree(T->RT,i+,j2,j1-);
return T;
}
int main()
{
int N;
cin >> N;
int num;
for(int i=;i<;i++)
for (int j = ; j < N; j++)
{
cin >> num;
Order[i].push_back(num);
}
Bt T=NULL;
T = BuildTree(T,,N,N);
queue<Bt> Q;
Q.push(T);
cout << T->Num;
while (!Q.empty())
{
if (Q.front()->LT)
{
Q.push(Q.front()->LT);
cout << " " << Q.front()->LT->Num;
}
if (Q.front()->RT)
{
Q.push(Q.front()->RT);
cout << " " << Q.front()->RT->Num;
}
Q.pop();
}
return ;
}