c语言 编写算法 以二叉链表存储的二叉树中交换二叉树各结点的左右子树
时间: 2023-10-18 22:11:43 浏览: 108
可以按照以下步骤编写算法:
1. 定义二叉树结点的结构体,包含数据域、左子树指针和右子树指针。
```c
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
```
2. 定义交换左右子树的函数,函数接受一个二叉树的根节点指针作为参数。
```c
void swap(TreeNode* root) {
if (root == NULL) {
return;
}
// 交换左右子树
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
// 递归交换左右子树
swap(root->left);
swap(root->right);
}
```
3. 测试函数。
```c
int main() {
// 构造二叉树
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->data = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->data = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->data = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->data = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->data = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->data = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 交换左右子树
swap(root);
// 遍历交换后的二叉树
printf("Inorder traversal of the swapped binary tree is: ");
inorder(root);
printf("\n");
return 0;
}
```
完整代码如下:
阅读全文