一、题目
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数N(≤30),是二叉树中结点的个数。第二行给出其中序遍历序列。第三行给出其前序遍历序列。数字间以空格分隔。
输出格式:
在一行中输出该树反转后的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。
输入样例:
7
1 2 3 4 5 6 7
4 1 3 2 6 5 7
输出样例:
4 6 1 7 5 3 2
二、方法1
1、思路
已知先序中序重构二叉树,然后层序遍历时先从右向左遍历即可。
(1)还原二叉树
①思路
以本题为例:
先序遍历为:4 1 3 2 6 5 7;中序遍历为:1 2 3 4 5 6 7
- 首先我们需要明白:对于先序遍历,其根节点位于头部;而对于中序遍历,其根节点位于中部;
- 根据这个规律,先从先序遍历中找到根节点 “4”,再观察中序遍历,以 “4” 为分界点,将二叉树序列分为两部分,其中 “1 2
3”为左子树,“5 6 7”为右子树,这样就找到了第一层; - 继续重复以上操作,以左子树为例,其先序遍历为 “1 3 2”,中序遍历为 “1 2 3”,其根节点为 “1”,观察中序遍历,以 “1” 为分界点,将其分为两部分,其中 “2 3”为右子树,无左子树;
②代码
LPNODE insert(int root, int start, int end)
{
LPNODE tree;
if (start > end)
return NULL;
int i;
for (i = start; i <= end; i++)
{
if (a[i] == b[root])
break;
}
tree = (LPNODE)malloc(sizeof(NODE));
tree->data = b[root];
tree->left = insert(root + 1, start, i - 1);
tree->right = insert(root + i - start + 1, i + 1, end);
return tree;
}
2、代码
#include<stdio.h>
#include<stdlib.h>
#define max 50
// 定义二叉树的节点结构体
typedef struct treeNode
{
int data;
struct treeNode* left;
struct treeNode* right;
}NODE, * LPNODE;
LPNODE insert(int root, int start, int end); // 二叉树的创建
void LayerOrder(LPNODE tree); // 层序镜像遍历
int n;
int i, j; // 计数
LPNODE Tree = NULL; // 二叉树
int a[max], b[max]; // a->中序 b->先序
int main()
{
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++)
{
scanf("%d", &b[i]);
}
Tree = insert(0, 0, n - 1);
LayerOrder(Tree);
return 0;
}
// 已知先序和中序,求二叉树
LPNODE insert(int root, int start, int end)
{
LPNODE tree;
if (start > end)
return NULL;
int i;
for (i = start; i <= end; i++)
{
if (a[i] == b[root])
break;
}
tree = (LPNODE)malloc(sizeof(NODE));
tree->data = b[root];
tree->left = insert(root + 1, start, i - 1);
tree->right = insert(root + i - start + 1, i + 1, end);
return tree;
}
// 层序镜像遍历
void LayerOrder(LPNODE tree)
{
if (tree == NULL)
return;
int flag = 0;
LPNODE queue[max];
int start = -1; int end = 0;
queue[end] = tree;
while (start != end)
{
start++;//保证输出的第一个数之前没有空格
if (flag)
printf(" ");
printf("%d", queue[start]->data);
flag++;
if (queue[start]->right != NULL) {
end++;
queue[end] = queue[start]->right;
}
if (queue[start]->left != NULL) {
end++;
queue[end] = queue[start]->left;
}
}
}