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

L2-011 玩转二叉树 (25分)_第1张图片

#include 
#include 

typedef struct node{
    int data;
    struct node *left;
    struct node *right;
}*BiTree;

BiTree createTreeByInAndPreOrder(int *In,int *Pre,int n);
BiTree ReverseTree(BiTree T);
void PrintlevelOrder(BiTree T);
int main(){
    int n,i;
    scanf("%d",&n);
    int In[n];
    int Pre[n];
    for(i=0;i<n;i++){
        scanf("%d",&In[i]);
    }
    for(i=0;i<n;i++){
        scanf("%d",&Pre[i]);
    }
    BiTree T = createTreeByInAndPreOrder(In,Pre,n);
    BiTree p = ReverseTree(T);
    PrintlevelOrder(p);
    return 0;
}
BiTree createTreeByInAndPreOrder(int *In,int *Pre,int n){
    if(n==0){
        return NULL;
    }
    int i = 0;
    while(In[i]!=Pre[0]){
        i++;
    }
    int leftNum = i;
    int rightNum = n-i-1;
    BiTree T = (BiTree)malloc(sizeof(struct node));
    T->data = Pre[0];
    T->left = createTreeByInAndPreOrder(&In[0],&Pre[1],leftNum);
    T->right = createTreeByInAndPreOrder(&In[leftNum+1],&Pre[leftNum+1],rightNum);
    return T;
}
BiTree ReverseTree(BiTree T){
    if(T == NULL){
        return T;
    }
        BiTree temp  = T->left; //这里temp可以不用申请空间,要申请也是对的
        T->left = T->right;
        T->right = temp;
        T->left = ReverseTree(T->left);
        T->right = ReverseTree(T->right);
        return T;
}
void PrintlevelOrder(BiTree T){
    BiTree Queue[31];
    int front= -1,rear = -1;
    Queue[++rear] = T;
    int count = 0;
    while(rear!=front){
        BiTree p = Queue[++front];
        if(count==0){
            printf("%d",p->data);
            count++;
        }else{
            printf(" %d",p->data);
        }
        if(p->left){
            Queue[++rear] = p->left;
        }
        if(p->right){
            Queue[++rear] = p->right;
        }
    }
    return;
}

你可能感兴趣的:(PTA天梯赛)