交换二叉树中所有结点的左右子树的位置

#include<stdlib.h>
#include<stdio.h>
#include<stack>
#define N 50
using namespace std;

typedef struct tree{
    char ch;
    struct tree *lchild;
    struct tree *rchild;
}BitTree; 

//数组输入
BitTree *CreateTree(int A[], int i, int n){
    BitTree *bt;
    if(i>n)
        return NULL;
    else{
        bt=(BitTree *)malloc(sizeof(BitTree));
        if(A[i]=='#')
            return NULL;
        bt->ch=A[i];
        bt->lchild=CreateTree(A, 2*i, n);
        bt->rchild=CreateTree(A, 2*i+1, n);
        return bt;
    }
} 

//层次遍历
void LayeredOrderTraverse(BitTree *bt);

//交换二叉树中所有结点的左右子树位置
void ExchangeBT(BitTree *bt){
    BitTree *QUEUE[N], *temp, *p=bt;
    int front = 0, rear = 1;
    if(p != NULL){
        QUEUE[0] = p;
        while(front < rear){
            p = QUEUE[front++];
            temp = p->lchild;
            p->lchild = p->rchild;
            p->rchild = temp;
            if(p->lchild != NULL)
                QUEUE[rear++] = p->lchild;
            if(p->rchild != NULL)
                QUEUE[rear++] = p->rchild;
        }
    }
} 

int main(){
    int A[N]={'#','A','B','C','D','E','#','F','G','H'};
    BitTree *bt=CreateTree(A,1,9);
    printf("pre-LayeredOrderTraverse:\n");
    LayeredOrderTraverse(bt);
    printf("\n");
    ExchangeBT(bt);
    printf("post-LayeredOrderTraverse:\n");
    LayeredOrderTraverse(bt);
    return 0; 
}

//层次遍历
void LayeredOrderTraverse(BitTree *bt){
    BitTree *QUEUE[N], *p;
    int front, rear;
    if(bt != NULL){
        QUEUE[0] = bt;
        front = 0;
        rear = 1;
        while(front < rear){
            p = QUEUE[front++];
            printf("%c ", p->ch);
            if(p->lchild != NULL)
                QUEUE[rear++] = p->lchild;
            if(p->rchild != NULL)
                QUEUE[rear++] = p->rchild;
        }
    }
}

 

转载于:https://www.cnblogs.com/exciting/p/10052011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值