给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
struct Nitree
{
int data;
Nitree *lchild;
Nitree *rchild;
Nitree(int a){data = a; lchild = rchild = NULL;} // 构造函数。
};
Nitree* build(int *in, int *pre, int n) // 一定要有返回值或者引用
{
if(n == 0)
return NULL;
Nitree *root = new Nitree(pre[0]);
int i = 0;
for(; i < n; i++)
if(in[i] == *pre)
break; //在中序遍历中找到根节点的位置
if(i > 0)
root->lchild = build(&in[0], &pre[1], i); //一定记得写root->lchild = !!!,传入新的前序中序数组区间
if(n-1-i > 0)
root->rchild = build(&in[i + 1], &pre[i + 1], n-1-i);
return root; // !!!不能忘
}
void LevelOrder(Nitree *root) //层序遍历用队列。
{
queue<Nitree *> q;
bool judge = 0;
if(root)
{
q.push(root);
while(!q.empty())
{
Nitree *temp = q.front();
if(judge == 0)
{
printf("%d",temp->data);
judge = 1;
}
else
printf(" %d",temp->data);
q.pop();
if(temp->rchild)
q.push(temp->rchild);
if(temp->lchild)
q.push(temp->lchild);
}
printf("\n");
}
}
int main()
{
int n;
cin>>n;
int in[30 + 5];
int pre[30 + 5];
for(int i = 0; i < n; i++)
scanf("%d",&in[i]);
for(int i = 0; i < n; i++)
scanf("%d",&pre[i]);
Nitree *root;
root = NULL;
root = build(in, pre, n); //传进去用的指针,所以写首地址。
LevelOrder(root);
return 0;}
这是一篇关于二叉树操作的博客,主要任务是给定二叉树的中序和前序遍历序列,首先对树进行镜面反转,然后输出反转后树的层序遍历序列。题目假设树的所有节点键值互不相同且为正整数。

501

被折叠的 条评论
为什么被折叠?



