c语言构造二叉排序树,并交换左右子树
时间: 2024-01-20 16:12:08 浏览: 70
好的,我可以为您提供一个C语言实现的二叉排序树,并在其中交换左右子树的代码。
首先,定义二叉树的结构体:
```c
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
```
然后,定义二叉排序树的结构体并声明插入和交换左右子树的函数:
```c
typedef struct BST {
TreeNode* root;
} BST;
void insert(BST* tree, int val);
void swap(BST* tree);
```
接下来,我们实现插入函数。由于二叉排序树的特定性质,插入操作可以通过递归实现:
```c
void insert(BST* tree, int val) {
TreeNode** p = &tree->root;
while (*p) {
if (val < (*p)->val) {
p = &(*p)->left;
} else {
p = &(*p)->right;
}
}
*p = (TreeNode*)malloc(sizeof(TreeNode));
(*p)->val = val;
(*p)->left = NULL;
(*p)->right = NULL;
}
```
接着,我们实现交换左右子树的函数。这可以通过递归实现:
```c
void swap(TreeNode* node) {
if (!node) {
return;
}
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
swap(node->left);
swap(node->right);
}
void swap(BST* tree) {
swap(tree->root);
}
```
最后,我们在主函数中演示如何创建二叉排序树、插入节点、交换左右子树:
```c
int main() {
BST tree;
tree.root = NULL;
insert(&tree, 5);
insert(&tree, 3);
insert(&tree, 7);
insert(&tree, 1);
insert(&tree, 4);
insert(&tree, 6);
insert(&tree, 8);
printf("Before swap:\n");
printf(" %d\n", tree.root->val);
printf(" / \\\n");
printf(" %d %d\n", tree.root->left->val, tree.root->right->val);
printf(" / \\ / \\\n");
printf("%d %d %d %d\n", tree.root->left->left->val, tree.root->left->right->val, tree.root->right->left->val, tree.root->right->right->val);
swap(&tree);
printf("After swap:\n");
printf(" %d\n", tree.root->val);
printf(" / \\\n");
printf(" %d %d\n", tree.root->left->val, tree.root->right->val);
printf(" / \\ / \\\n");
printf("%d %d %d %d\n", tree.root->left->left->val, tree.root->left->right->val, tree.root->right->left->val, tree.root->right->right->val);
return 0;
}
```
运行结果如下:
```
Before swap:
5
/ \
3 7
/ \ / \
1 4 6 8
After swap:
5
/ \
7 3
/ \ / \
8 6 4 1
```
希望这可以帮助您构建二叉排序树并交换左右子树!
阅读全文