当前位置:网站首页>玩转二叉树 (25 分)

玩转二叉树 (25 分)

2022-04-23 08:35:00 怀化第二深情

给定一棵二叉树的中序遍历和前序遍历,请你先将树做个镜面反转,再输出反转后的层序遍历的序列。所谓镜面反转,是指将所有非叶结点的左右孩子对换。这里假设键值都是互不相等的正整数。

输入格式:

输入第一行给出一个正整数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<bits/stdc++.h>
using namespace std;
const int N=40;
map<int,int>l,r,pos;
int post[N],in[N];
int n,cnt;
int build(int il,int ir,int pl,int pr){
	int root=post[pl];
	int k=pos[root];
	if(il<k)l[root]=build(il,k-1,pl+1,pl+k-il);
	if(ir>k)r[root]=build(k+1,ir,pl+k-il+1,pr);
	return root;
}
void bfs(int root)                          //BFS用来层序遍历输出
{
	queue<int> q;
	q.push(root);
	while (q.size())
	{
		auto t = q.front();
		q.pop();
		if(cnt==0)cout<<t;
		else cout <<" "<<t;
		cnt++;
		if (r.count(t)) q.push(r[t]);       //存在则加入队列,等待下一层遍历
		if (l.count(t)) q.push(l[t]);       //判断该节点的左右儿子是否存在

	}
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>in[i];
		pos[in[i]]=i;
	}
	for(int i=0;i<n;i++)cin>>post[i];
	int root=build(0,n-1,0,n-1);
	bfs(root);
	return 0;
}

 

版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124340070