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<stdio.h> #include<stdlib.h> #include<iostream> #include<queue> using namespace std; struct Node { struct Node *lchild; int data; struct Node *rchild; }; int result[35]; //根据先序遍历和中序遍历恢复二叉树 struct Node *createTree(int pre[],int i,int j,int order[],int k,int h) { struct Node *bt; bt=(struct Node *)malloc(sizeof(struct Node)); bt->data=pre[i]; bt->lchild=NULL; bt->rchild=NULL; int m=k; while(order[m]!=pre[i]) m++; if(m!=k) bt->lchild=createTree(pre,i+1,i+m-k,order,k,m-1); if(m!=h) bt->rchild=createTree(pre,i+m-k+1,j,order,m+1,h); return bt; } //反转二叉树 void reverse(struct Node *bt) { if(bt==NULL)return ; struct Node *lchild; struct Node *rchild; lchild=bt->lchild; rchild=bt->rchild; bt->lchild=rchild; bt->rchild=lchild; reverse(bt->lchild); reverse(bt->rchild); } //层次遍历二叉树输出结果 void print(struct Node *q) { if(q==NULL)return; int i=0; queue<struct Node*> p; p.push(q); while( !p.empty() ) { struct Node *t; t=p.front(); result[i++]=t->data; // printf("%d ",t->data); p.pop(); if( t->lchild!=NULL ) { p.push(t->lchild); } if( t->rchild!=NULL ) { p.push(t->rchild); } } } int main() { int n; while(~scanf("%d",&n)) { int pre[35]; int order[35]; int i; for( i=1;i<=n;i++ ) scanf("%d",&order[i]); for( i=1;i<=n;i++ ) scanf("%d",&pre[i]); struct Node *bt; bt=createTree(pre,1,n,order,1,n); //print(bt); reverse(bt); print(bt); for(i=0;i<n;i++) { if(i+1==n)printf("%d\n",result[i]); else printf("%d ",result[i]); } } return 0; }