L2-011 玩转二叉树

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

输入格式:
输入第一行给出一个正整数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

AC代码以及分析如下:

#include<bits/stdc++.h>
using namespace std;
struct tree{
	int l,r;
};
tree tr[32];
int in[32],pre[32];
vector<int>ans;
	
//由中序遍历和后序遍历递归建树
int build(int il,int ir,int pl,int pr)
{
	if(il>ir||pl>pr)return 0;
	int root=pre[pl]; //先序遍历第一个数即为根
	int jump=il;
	while(in[jump]!=root)jump++; //找出当前根节点在中序遍历数组中的位置
	int cnt=jump-il; //左子树的节点数
	tr[root].l=build(il,jump-1,pl+1,pl+cnt);
	tr[root].r=build(jump+1,ir,pl+1+cnt,pr);
	return root;
}

//层序遍历,题目中反转 -> 即先遍历右子树,再遍历左子树
void bfs(int root)
{
	queue<int>q;
	q.push(root);
	while(!q.empty()){
		int rt=q.front();
		q.pop();
		ans.push_back(rt);
		if(tr[rt].r)q.push(tr[rt].r);
		if(tr[rt].l)q.push(tr[rt].l);
	}
//遍历的第二种方法
//    queue<int> q;
//    q.push(rt);
//    ans.push_back(rt);
//    while(!q.empty())
//    {
//        int t=q.front();
//        q.pop();
//        if(tr[t].r!=0)
//        {
//            q.push(tr[t].r);
//            ans.push_back(tr[t].r);
//        }
//        if(tr[t].l!=0)
//        {
//            q.push(tr[t].l);
//            ans.push_back(tr[t].l);
//        }
//    }
}

int main()
{
	int n;

	cin>>n;
    for(int i=0;i<n;++i){
        cin>>in[i];
    }
    for(int i=0;i<n;++i){
    	cin>>pre[i];
	}
    int root=build(0,n-1,0,n-1);
    bfs(root);
    for(int i=0;i<ans.size();++i){
    	if(i==ans.size()-1){
    		cout<<ans[i];
		}else cout<<ans[i]<<" ";
	}
    return 0;
}
posted @ 2022-10-18 08:47  aw11  阅读(63)  评论(0)    收藏  举报