设计在链式存储结构上交换二叉树中所有结点左右子树的算法(C语言版)

#include <stdio.h>
#include <stdlib.h>

// 二叉树节点结构
typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;

// 创建新的二叉树节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

// 交换二叉树中所有节点的左右子树
void swapSubtrees(Node* root) {
    if (root == NULL) {
        return;
    }

    // 递归交换左右子树
    Node* temp = root->left;
    root->left = root->right;
    root->right = temp;

    swapSubtrees(root->left);
    swapSubtrees(root->right);
}

// 打印二叉树(中序遍历)
void printTree(Node* root) {
    if (root == NULL) {
        return;
    }

    printTree(root->left);
    printf("%d ", root->data);
    printTree(root->right);
}

int main() {
    // 创建二叉树
    Node* root = createNode(1);
    root->left = createNode(2);
    root->right = createNode(3);
    root->left->left = createNode(4);
    root->left->right = createNode(5);

    // 打印原始二叉树
    printf("原始二叉树:");
    printTree(root);
    printf("\n");

    // 交换二叉树中所有节点的左右子树
    swapSubtrees(root);

    // 打印交换后的二叉树
    printf("交换后的二叉树:");
    printTree(root);
    printf("\n");

    // 释放内存
    // ...

    return 0;
}
 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值