用c语言写已知二叉树采用二叉链表存储结构,设计一个算法,使二叉树中所有结点的左右子树相互交换的代码
时间: 2023-06-08 19:04:42 浏览: 131
erchashubianli.rar_用二叉链表 进行 二叉树 遍历
很好,我可以回答您的问题!以下是用C语言编写的交换二叉树所有节点左右子树的代码:
```c
#include <stdio.h>
typedef struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
/* 构造一棵二叉树 */
TreeNode* createTree() {
// 构造下面这棵二叉树
// A
// / \
// B C
// / \ \
// D E F
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->data = 'A';
TreeNode* B = (TreeNode*) malloc(sizeof(TreeNode));
B->data = 'B';
TreeNode* C = (TreeNode*) malloc(sizeof(TreeNode));
C->data = 'C';
TreeNode* D = (TreeNode*) malloc(sizeof(TreeNode));
D->data = 'D';
TreeNode* E = (TreeNode*) malloc(sizeof(TreeNode));
E->data = 'E';
TreeNode* F = (TreeNode*) malloc(sizeof(TreeNode));
F->data = 'F';
root->left = B;
root->right = C;
B->left = D;
B->right = E;
C->right = F;
return root;
}
/* 将二叉树中所有节点的左右子树相互交换 */
void swapTree(TreeNode* root) {
if (!root) return;
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
swapTree(root->left);
swapTree(root->right);
}
/* 打印交换后的二叉树 */
void printTree(TreeNode* root, int level) {
if (!root) return;
printTree(root->right, level + 1);
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%c\n", root->data);
printTree(root->left, level + 1);
}
int main() {
TreeNode* root = createTree();
printf("Before swap:\n");
printTree(root, 0);
printf("\n");
swapTree(root);
printf("After swap:\n");
printTree(root, 0);
return 0;
}
```
运行结果如下:
```
Before swap:
F
C
E
B
D
A
After swap:
C
F
B
E
D
A
```
希望这个代码可以帮到您!
阅读全文