L2-011. 玩转二叉树
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。
输入格式:
输入第一行给出一个正整数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 <algorithm>
#include <queue>
using namespace std;
const int MAX = 1005;
struct node{
int l;
int r;
}s[MAX];
int mid[MAX];//中序
int pro[MAX];//前序
//由前序和中序确定一棵二叉树(模拟建树)
int built(int p,int q,int n){
if(n == 0)
return 0;
int x = pro[p];
int p1 = q,t;
while(mid[p1]!=x)p1++;
t = p1-q;
s[x].l = built(p+1,q,t);
s[x].r = built(p+t+1,q+t+1,n-t-1);
return x;
}
//层次遍历
void cengci(int root){
queue<int>Q;
Q.push(root);
int flag = 0;
while(!Q.empty()){
int x = Q.front();
Q.pop();
if(x == 0)
break;
if(!flag){
cout<<x;
flag=1;
}
else
cout<<" "<<x;
if(s[x].r)
Q.push(s[x].r);
if(s[x].l)
Q.push(s[x].l);
}
cout<<endl;
return ;
}
int main(){
int n;
while(cin>>n){
for(int i=0;i<n;i++)
cin>>mid[i];
for(int i=0;i<n;i++)
cin>>pro[i];
built(0,0,n);
int x = pro[0];
cengci(x);
}
return 0;
}
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
using namespace std;
bool fist;
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)
{
if(length==0)return NULL;//终止条件
tree_node* temp = new tree_node;
int pos;
for(pos=0;pos<length;pos++)//找到根节点->然后根据中序遍历把左子树和右子树分开
{
if(in[pos]==pre[0])break;
}
temp->value=pre[0];
temp->leftchild=build_tree(pre+1,in,pos);
temp->rightchild=build_tree(pre+pos+1,in+pos+1,length-pos-1);
return temp;
}
void dfs(tree_node* tree)
{
queue<tree_node*>Q;
while(!Q.empty())Q.pop();
Q.push(tree);
tree_node* root;
while(!Q.empty())
{
root=Q.front();
Q.pop();
if(!fist)
{
cout<<root->value;
fist=true;
}
else cout<<" "<<root->value;
if(root->rightchild!=NULL)
{
tree_node* rchild=root->rightchild;
Q.push(rchild);
}
if(root->leftchild!=NULL)
{
tree_node* lchild=root->leftchild;
Q.push(lchild);
}
}
cout<<endl;
}
int main()
{
int n;
int pre[maxn],in[maxn];
while(scanf("%d",&n)==1)
{
fist=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);
dfs(tree);
}
}