L2-011 玩转二叉树 (25 分)

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

输入格式:

输入第一行给出一个正整数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<queue>
#include<vector>
using namespace std;
int a[31],b[31];
queue<int>q;
vector<int>v;
vector<int>::iterator it;
struct treenode
{
    int l,r;
}t[31];
int findtree(int a1,int a2,int b1,int b2)//参数表示在数组a,b中的初末位置 
{
    int root,pos,i;
    if (a2-a1==0)//长度为1,为叶节点 
        return b1;
    if (a2-a1<0)
        return -1;
    root=b1;
    for (i=a1;i<=a2;i++)//在中序遍历中找根节点 
        if (b[root]==a[i])
        {
            pos=i;break;
        }
    t[root].l=findtree(a1,pos-1,b1+1,b1+pos-a1);
    t[root].r=findtree(pos+1,a2,b1+pos-a1+1,b2);
    return root;//返回根节点位置 
}
void printtree(int n)
{
    int temp;
    q.push(n);
    while (!q.empty())//队列为空则层序遍历结束 
    {
        temp=q.front();
        q.pop();
        v.push_back(b[temp]);//将根节点放入容器 
        if (t[temp].r!=-1)
            q.push(t[temp].r);
        if (t[temp].l!=-1)
            q.push(t[temp].l);//若左右子节点存在则放入队列 
    }
}
int main()
{
    int n,i;
    cin>>n;
    for (i=0;i<n;i++)
    {
        t[i].l=t[i].r=-1;
        cin>>a[i];
    }
    for (i=0;i<n;i++)
        cin>>b[i];
    findtree(0,n-1,0,n-1);//树的重建 
    printtree(0);//层序遍历 
    cout<<*v.begin();
    for (it=v.begin()+1;it!=v.end();it++)
        cout<<' '<<*it;
    return 0;
}

 

posted @ 2019-03-29 16:37  20190315  阅读(760)  评论(0)    收藏  举报