以二叉链表作为二叉树的存储结构,编写以下算法,交换二叉树每个结点的左孩子和右孩子。用c语言
时间: 2023-11-15 19:06:55 浏览: 192
来实现该算法。
答案:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* invertTree(struct TreeNode* root) {
if (root == NULL) {
return NULL;
}
struct TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
return root;
}
int main() {
// 创建二叉树
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->val = 2;
root->right->val = 3;
root->left->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->left->left->val = 4;
root->left->right->val = 5;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right->left = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->right = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->right->left->val = 6;
root->right->right->val = 7;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right->left = NULL;
root->right->right->right = NULL;
// 前序遍历输出原二叉树
printf("Original tree: ");
preOrder(root);
printf("\n");
// 交换左右子树
invertTree(root);
// 前序遍历输出交换后的二叉树
printf("Inverted tree: ");
preOrder(root);
printf("\n");
return 0;
}
void preOrder(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
阅读全文