#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;
}