L2-011. 玩转二叉树

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<string.h>
#include<math.h>
#include<iostream>
#include<string>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
int a[50],b[50],c[50];
int o;
struct tree
{
	int tl,tr,tl1,tr1;
};
void bfs(int l,int r,int l1,int r1)
{
	tree node;
	queue<tree> q;
	node.tl=l;
	node.tr=r;
	node.tl1=l1;
	node.tr1=r1;
	q.push(node);
	while(!q.empty())
	{
		tree node2=q.front();
		q.pop();
		int t=b[node2.tl1];
		c[o++]=t;
		int mid;
		for(int i=node2.tl;i<=node2.tr;i++)
		{
			if(t==a[i])
			{
				mid=i;				
				break;
			}
		}
		node.tl=mid+1;
		node.tr=node2.tr;
		node.tl1=node2.tl1+(mid-node2.tl)+1;
		node.tr1=node2.tr1;
		if(node.tl<=node.tr&&node.tl1<=node.tr1)
		q.push(node);//right
		node.tl=node2.tl;
		node.tr=mid-1;
		node.tl1=node2.tl1+1;
		node.tr1=node2.tl1+(mid-node2.tl);
		if(node.tl<=node.tr&&node.tl1<=node.tr1)
		q.push(node);//left
				
	}
}
int main()
{
	int n,i,j;
	scanf("%d",&n);
	for(i=0;i<n;i++)
	scanf("%d",&a[i]);
	for(i=0;i<n;i++)
	scanf("%d",&b[i]);
	o=0;
	bfs(0,n-1,0,n-1);
	for(i=0;i<o-1;i++)
	printf("%d ",c[i]);
	printf("%d\n",c[o-1]);
}

猜你喜欢

转载自blog.csdn.net/thewise_lzy/article/details/79560669
今日推荐