C语言交换二叉树中每个结点的左孩子和右孩子
时间: 2023-11-14 21:07:20 浏览: 42
可以使用递归的方法交换二叉树中每个节点的左孩子和右孩子。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构体
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
// 递归交换二叉树中每个节点的左孩子和右孩子
void swapLeftAndRight(struct TreeNode* root) {
if (root == NULL) {
return;
}
struct TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
swapLeftAndRight(root->left);
swapLeftAndRight(root->right);
}
// 打印二叉树
void printTree(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
printTree(root->left);
printTree(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->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->val = 3;
root->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 4;
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right->val = 5;
// 交换二叉树的左右孩子
swapLeftAndRight(root);
// 打印交换后的二叉树
printTree(root);
return 0;
}
```
输出结果为:3 2 5 4
说明二叉树中每个节点的左孩子和右孩子都被成功交换了。