编写C语言程序,将一棵二叉树中所有结点的左、右子女
时间: 2024-03-09 15:45:52 浏览: 62
的值交换。
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void swapChild(struct TreeNode* root) {
if(root == NULL) return;
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
swapChild(root->left);
swapChild(root->right);
}
int main() {
// 假设二叉树已经存在并且被初始化
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->left->left = NULL;
root->left->right = NULL;
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->right->left = NULL;
root->right->right = NULL;
swapChild(root);
// 输出交换后的二叉树结构
printf("root: %d\n", root->val);
printf("root->left: %d\n", root->left->val);
printf("root->right: %d\n", root->right->val);
return 0;
}
```
运行结果为:
```
root: 1
root->left: 3
root->right: 2
```
可以看到,左、右子女的值已经交换成功。
阅读全文