0
点赞
收藏
分享

微信扫一扫

pta L2-011 玩转二叉树

那小那小 2022-02-06 阅读 74

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

 代码如下:

用的数据结构写的队列  因为本人还太菜不会用stl啥的 233 写了好久 记录一下

#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode{
    int data;
    BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct QueueNode{
    BiTree data;
    struct QueueNode *next;
}QueueNode ,*QueuePtr;
typedef struct{
    QueuePtr front;
    QueuePtr rear;
}LinkQueue;
int a[32],o;
void initQueue(LinkQueue &Q){
    Q.front=(QueueNode *)malloc(sizeof(QueueNode));
    if(!Q.front)
    exit(-1);
    Q.rear=Q.front;
    Q.front->next=NULL;
    return ;
}
void enQueue(LinkQueue &Q,BiTree &T){//树节点的进队 
    QueuePtr p;
    p=(QueueNode *)malloc(sizeof(QueueNode));
    p->data=T;
    p->next=NULL;
    Q.rear->next=p;
    Q.rear=p;
    return ;
}
bool Empty(LinkQueue Q){//判断队列是否为空 
    if(Q.rear==Q.front)
    return true;
    else 
    return false;
}
BiTree DeQueue(LinkQueue &Q){
    QueuePtr p;
    BiTree q;
    if(Q.front==Q.rear)
    return 0;
    p=Q.front->next;
    if(!p)
    exit(-1);
    else{
        q=p->data;
        a[o]=q->data;//把数据存到数组 最后输出 行末不得有空格 
        o++;
        //cout<<q->data<<" ";
        Q.front->next=p->next;
        if(Q.rear==p)
        Q.rear=Q.front;//防止rear指针丢失 
        free(p);
        return q;
    }
}
BiTree build(int *pre,int *in,int size){//递归分治来进行二叉树的还原(根据前序序列和中序序列) 
    if(size<=0) return NULL;
    int i;
    for(i=0;i<size;i++){
        if(in[i]==pre[0])
        break;
    }
    BiTree tree=(BiTNode *)malloc(sizeof(BiTNode));
    tree->data=pre[0];
    tree->lchild=build(pre+1,in,i);//左子树的归位 
    tree->rchild=build(pre+i+1,in+i+1,size-i-1);//右子树的归位 
    return tree;
}

void levelorderTraverse(BiTree &T){
    LinkQueue Q;
    initQueue(Q);
    enQueue(Q,T);
    while(!Empty(Q)){
        T=DeQueue(Q);
        if(T->rchild)
        enQueue(Q,T->rchild);//先从右节点开始 
        if(T->lchild)
        enQueue(Q,T->lchild);//向左节点层次遍历 
    }
}
int main(){
    int pre[100],in[100];
    int n;
    cin>>n;//数的个数 
    for(int i=0;i<n;i++)
    cin>>in[i];//中序序列的输入 
    for(int i=0;i<n;i++)
    cin>>pre[i];//前序序列的输入 
    BiTree T;
    T=build(pre,in,n);//根据前中序列来进行二叉树的复原 
    levelorderTraverse(T);//层次遍历 ,利用队列来进行层次,顺便交换左右子树 
    for(int i=0;i<o;i++){
        cout<<a[i];
        if(i!=o-1)
        cout<<" ";
    }
    return 0;
}

举报

相关推荐

0 条评论