交换左右子树

来源:互联网 发布:采购办公软件 编辑:程序博客网 时间:2024/05/23 11:50
#include <stdio.h>#include <stdlib.h>#define MAXSIZE 20typedef struct node{    char data;    node * lchild;    node * rchild;}BTree;typedef struct{    BTree * data[MAXSIZE];    int rear;    int front;}SeqQueue;SeqQueue * init(){    SeqQueue * p;    p = (SeqQueue *)malloc(sizeof(SeqQueue));    p->rear = p->front = 0;    return p;}void inQueue(SeqQueue * p,BTree * x){    if((p->rear + 1) % MAXSIZE == p->front){        printf("队列已满!\n");    }else{        p->rear = (p->rear + 1) % MAXSIZE;        p->data[p->rear] = x;    }}BTree * outQueue(SeqQueue * p){    BTree * temp;    if(p->front == p->rear){        printf("队列已空!\n");        temp = NULL;    }else{        p->front = (p->front + 1) % MAXSIZE;        temp = p->data[p->front];    }    return temp;}BTree * create(BTree * p){    char ch;    scanf("%c",&ch);    if(ch != ' '){        p = (BTree *)malloc(sizeof(BTree));        p->data = ch;        p->lchild = create(p->lchild);        p->rchild = create(p->rchild);        return p;    }else{        return NULL;    }}void change(BTree * p){     //递归的交换左右子树    BTree * q;    if(p != NULL){        q = p->lchild;        p->lchild = p->rchild;        p->rchild = q;        change(p->lchild);        change(p->rchild);    }   }BTree * change2(SeqQueue * q,BTree * p){    //非递归的交换左右子树    BTree * temp,* k;    if(p != NULL){        inQueue(q,p);    }else{        return NULL;    }    while(q->rear != q->front){        k = outQueue(q);        temp = k->lchild;        k->lchild = k->rchild;        k->rchild = temp;        if(k->lchild != NULL){            inQueue(q,k->lchild);        }        if(k->rchild != NULL){            inQueue(q,k->rchild);        }       }    return p;}void preorder(BTree * p){    if(p != NULL){        printf("%4c",p->data);        preorder(p->lchild);        preorder(p->rchild);    }   }int main(){    BTree * p , * k;    SeqQueue * q;    p = create(p);    q = init();    printf("先序遍历:\n");    preorder(p);    printf("\n");    change(p);    printf("递归交换左右子树(先序遍历):\n");    preorder(p);    printf("\n");    k = change2(q,p);    if(k != NULL){        printf("非递归交换左右子树(先序遍历):\n");        preorder(k);        printf("\n");    }else{        printf("错误!\n");    }       return 0;}
0 0
原创粉丝点击