题目:
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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<cstring>
#include<queue>
#include<stdio.h>
using namespace std;
bool first;
const int maxn=40;
struct tree_node
{
int value;
tree_node* leftchild;
tree_node* rightchild;
tree_node()
{
leftchild=NULL;
rightchild=NULL;
}
};
tree_node* build_tree(int pre[],int in[],int length)//in是终须遍历,pre是前序遍历
{
if(length==0)
return NULL;
int pos;
for(pos=0;pos<length;pos++)
{
if(in[pos]==pre[0])
break;//找到中序中的最先出现的前序
}
tree_node *temp=new tree_node;
temp->value=pre[0];
temp->leftchild=build_tree(pre+1,in,pos);
temp->rightchild=build_tree(pre+pos+1,in+1+pos,length-1-pos);//把前序,中序中中左子树的点去掉
return temp;
}
/*void back(tree_node *node)//后序遍历
{
if(node!=NULL)
{
back(node->leftchild);
back(node->rightchild);
printf("%d",node->value);
}
}*/
void bfs(tree_node* tree)
{
queue<tree_node*>Q;
Q.push(tree);
while(!Q.empty())
{
tree_node* cur=new tree_node;
cur=Q.front();
Q.pop();
if(cur->rightchild!=NULL)
Q.push(cur->rightchild);
if(cur->leftchild!=NULL)
Q.push(cur->leftchild);
if(first)
{
cout<<" "<<cur->value;
}
else
{
cout<<cur->value;
first=1;
}
}
cout<<endl;
}
int main()
{
int n;
int pre[maxn],in[maxn];
scanf("%d",&n);
first=false;
//input
for(int i=0;i<n;i++)scanf("%d",&in[i]);
for(int i=0;i<n;i++)scanf("%d",&pre[i]);
//solve
tree_node* tree=build_tree(pre,in,n);
//back(tree);
bfs(tree);
}