C++二叉树左右子树交换及层次遍历测试(直接复制粘贴运行,无需修改)

#include<iostream>
#include<stdlib.h>

// 定义二叉树节点结构体
typedef struct TB {
    struct TB* lchild;  // 左子树指针
    struct TB* rchild;  // 右子树指针
    int data;  // 节点数据
} BTnode, *BTree;

// 交换二叉树左右子树的函数
void Exchange(BTree &T) {
    // 如果树为空或为叶子节点,直接返回
    if (T == NULL || (T->lchild == NULL && T->rchild == NULL)) {
        return;
    }
    int front = 0, last = 1;
    BTree s[99], p = T, t;
    s[0] = T;
    // 层次遍历树的节点
    while (front < last) {
        p = s[front++];
        // 将有左右子树的节点的左右子树交换
        if (p->lchild && p->rchild) {
            t = p->lchild;
            p->lchild = p->rchild;
            p->rchild = t;
        }
        // 将子树节点加入队列继续遍历
        if (p->lchild) s[last++] = p->lchild;
        if (p->rchild) s[last++] = p->rchild;
    }
}

// 层次遍历二叉树的函数
void Cenci4(BTree T) {
    BTree p = T, q, s[99];
    int front = 0, last = 1, level = 0, index = 0;
    s[front] = p;
    // 层次遍历
    while (front < last) {
        while (front <= index) {
            p = s[front++];
            printf("%d", p->data);
            if (p->lchild) s[last++] = p->lchild;
            if (p->rchild) s[last++] = p->rchild;
        }
        printf("\n");
        index = last - 1;
        level++;
    }
}

int main() {
    // 动态分配内存创建二叉树
    BTree T = (BTree)malloc(sizeof(BTnode)), t1, t2, t3, t4, t5;
    T->data = 0;
    T->lchild = (BTree)malloc(sizeof(BTnode));
    T->rchild = (BTree)malloc(sizeof(BTnode));
    t1 = T->lchild;
    t2 = T->rchild;
    t1->data = 1;
    t2->data = 2;
    t1->lchild = NULL;
    t1->rchild = NULL;
    t2->lchild = (BTree)malloc(sizeof(BTnode));
    t2->rchild = (BTree)malloc(sizeof(BTnode));
    t3 = t2->lchild;
    t4 = t2->rchild;
    t3->data = 3;
    t4->data = 4;
    t3->lchild = NULL;
    t3->rchild = NULL;
    t4->lchild = NULL;
    t4->rchild = NULL;

    // 输出交换前的层次遍历
    printf("交换前:\n");
    Cenci4(T);

    // 执行交换操作
    Exchange(T);

    // 输出交换后的层次遍历
    printf("交换后:\n");
    Cenci4(T);

    return 0;
}

在main()中交换前的二叉树:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值