交换左右子树

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20

typedef 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值