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<bits/stdc++.h>
using namespace std;
struct node
{
    node *l,*r;
    int data;
};
int previous[100],middle[100];
node *creat(int l1,int r1,int l2,int r2)//前序区间,中序区间
{
    if(l1>r1||l2>r2)
        return NULL;
    node *root=new node;
    root->data=previous[l1];
    root->l=NULL;
    root->r=NULL;
    int k;
    for(k=l2;k<=r2;k++)
    {
        if(middle[k]==previous[l1])
            break;
    }
    int num=k-l2;
    root->l=creat(l1+1,l1+num,l2,k-1);
    root->r=creat(l1+num+1,r1,k+1,r2);
    return root;
}
void layershow(node *root)
{
    queue<node*>que;
    if(root)
    {
        que.push(root);
        cout<<que.front()->data;
    }
    while(!que.empty())
    {
        node *root=que.front();
        que.pop();
        if(root->r)
        {
            cout<<" "<<root->r->data;
            que.push(root->r);
        }
        if(root->l)
        {
            cout<<" "<<root->l->data;
            que.push(root->l);
        }
    }
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>middle[i];
    for(int i=0;i<n;i++)
        cin>>previous[i];
    node *root=creat(0,n-1,0,n-1);
    layershow(root);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43824158/article/details/88605623
今日推荐