PTA 7-3 树的遍历 (25分)
PTA 7-3 树的遍历 (25分)
给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
【程序思路】
在后序遍历的最后一个数字4是根结点,在中序遍历中找到根结点4,4左边的序列1 2 3共3个结点是左子树的中序遍历,4右边的序列5 6 7共3个结点是右子树的中序遍历。在后序遍历中前3个结点2 3 1是左子树的后序遍历,紧接着的3个结点5 7 6是右子树的后序遍历。即变成了两个子树的后序遍历和中序遍历序列以及根结点。
左子树的后序遍历为2 3 1
左子树的中序遍历为1 2 3
右子树的后序遍历为5 7 6
右子树的中序遍历为5 6 7
根结点为4
按同样的步骤可以将左子树也分成左子树、右子树和根这3部分,右子树也可以分成左子树、右子树和根这3部分。
然后递归创建树,最后利用队列层序遍历输出。
【程序实现】
#include <bits/stdc++.h>
using namespace std;
typedef struct Tree{
int data;
struct Tree *left;
struct Tree *right;
}*tree;
int p1[35],p2[35];
struct Tree *creat(int front1, int rear1, int front2, int rear2) {
struct Tree *root = new struct Tree;
root->data = p1[rear1];
root->left = root->right = NULL;
int p = front2;
while(p2[p] != p1[rear1])
p++;
int c = p - front2;//左子树节点的个数
if (p != front2) //创建左子树
root->left = creat(front1 , front1 + c - 1 , front2 , p - 1);
if (p != rear2)//创建右子树
root->right = creat(front1 + c , rear1 - 1 , p + 1 , rear2);
return root;
}
void Visit(struct Tree *root) {
queue<tree> q;
if (root)
q.push(root);
while(!q.empty()) {
root = q.front();
q.pop();
cout<<root->data;
if (root->left)
q.push(root->left);
if (root->right)
q.push(root->right);
if (!q.empty())
cout<<' ';
}
}
int main()
{
int n;
cin>>n;
for(int i = 0; i < n; i++)
cin>>p1[i];
for(int i = 0; i < n; i++)
cin>>p2[i];
struct Tree *root = creat(0, n - 1, 0, n - 1);
Visit(root);
return 0;
}

浙公网安备 33010602011771号