设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写递归算法交换该二叉树的左右孩子。用C语言写
时间: 2024-05-10 16:15:23 浏览: 166
以下是C语言的递归算法实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 先序遍历建立二叉树
TreeNode* createBinaryTree() {
char c;
scanf("%c", &c);
if (c == '#') {
return NULL;
}
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = c;
root->left = createBinaryTree();
root->right = createBinaryTree();
return root;
}
// 交换左右孩子
void exchangeChild(TreeNode *root) {
if (root == NULL) {
return;
}
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
exchangeChild(root->left);
exchangeChild(root->right);
}
// 先序遍历输出二叉树
void preOrder(TreeNode *root) {
if (root == NULL) {
printf("# ");
return;
}
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
int main() {
printf("请按先序遍历输入二叉树,用#表示空结点:\n");
TreeNode *root = createBinaryTree();
printf("交换前的二叉树:\n");
preOrder(root);
printf("\n");
exchangeChild(root);
printf("交换后的二叉树:\n");
preOrder(root);
printf("\n");
return 0;
}
```
输入样例:
```
请按先序遍历输入二叉树,用#表示空结点:
AB#C##DE#G##
```
输出样例:
```
交换前的二叉树:
A B # # C # # D E # G # #
交换后的二叉树:
A C # # B # # G E # D # #
```
阅读全文