版权声明:大鹏专属 https://blog.csdn.net/NCC__dapeng/article/details/88656839
天梯赛虽然落选,但依旧会努力的继续往前走,挫折不代表终点,而是浴火重生的新的起点,共勉!
题目大意:
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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
思路:思路比较简单,就是根据两种遍历方式,进行建树操作,然后进行左右交换的层次遍历,由于这个太长时间没有接触,忘记了建树过程,所以没能AC。
在这里推荐三篇关于建树与层次遍历的博客,初级建树,建树模板,四种遍历方式。
这里尤其注意如何建树(割裂法)!!!
下面给出AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=5000+10;
int pre[maxn];
int in[maxn];
struct node
{
int elem;
struct node *left;
struct node *right;
}*Tree;
node* Build_Tree(int *pre,int *in,int len)
{
if(len==0) return NULL;
node *T=new node();
T->elem=pre[0];
int rootindex=0;
for(;rootindex<len;rootindex++)
{
if(in[rootindex]==pre[0])
{
break;
}
}
T->left=Build_Tree(pre+1,in,rootindex);
T->right=Build_Tree(pre+rootindex+1,in+rootindex+1,len-(rootindex+1));
return T;
}
void levelorder(node *T)
{
node *a[100000];
int l=0,r=1;
a[0]=T;
bool flag=true;
while(l<r)
{
node* t=a[l++];
if(!flag) printf(" %d",t->elem);
else printf("%d",t->elem),flag=false;
if(t->right!=NULL) a[r++]=t->right;
if(t->left!=NULL) a[r++]=t->left;
}
}
int main()
{
int n; scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&in[i]);
for(int i=0;i<n;i++) scanf("%d",&pre[i]);
Tree=Build_Tree(pre,in,n);
levelorder(Tree);
return 0;
}