c语言用递归的方法实现以下算法: 1.以二叉链表表示二叉树,建立一棵二叉树(算法 5.3); 2.输出二叉树的中序遍历结果(算法 5.1); 3.输出二叉树的前序遍历结果(见讲稿); 4.输出二叉树的后序遍历结果(见讲稿) 并举一个输出案例
时间: 2024-01-22 17:17:57 浏览: 88
C语言实现二叉树的前序、中序、后续遍历(递归法)
以下是用递归实现建立一棵二叉树的算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode *createTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
printf("Enter left child of %d: \n", data);
root->left = createTree();
printf("Enter right child of %d: \n", data);
root->right = createTree();
return root;
}
```
以下是用递归实现中序遍历二叉树的算法:
```c
void inorder(TreeNode *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
```
以下是用递归实现前序遍历二叉树的算法:
```c
void preorder(TreeNode *root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
```
以下是用递归实现后序遍历二叉树的算法:
```c
void postorder(TreeNode *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
```
下面是一个示例代码,建立了一棵二叉树并输出了它的中序遍历、前序遍历和后序遍历结果:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode *createTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
printf("Enter left child of %d: \n", data);
root->left = createTree();
printf("Enter right child of %d: \n", data);
root->right = createTree();
return root;
}
void inorder(TreeNode *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
void preorder(TreeNode *root) {
if (root != NULL) {
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(TreeNode *root) {
if (root != NULL) {
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
}
int main() {
printf("Enter the root node: ");
TreeNode *root = createTree();
printf("Inorder traversal: ");
inorder(root);
printf("\n");
printf("Preorder traversal: ");
preorder(root);
printf("\n");
printf("Postorder traversal: ");
postorder(root);
printf("\n");
return 0;
}
```
示例输入为:
```
Enter the root node: 1
Enter left child of 1:
2
Enter left child of 2:
-1
Enter right child of 2:
-1
Enter right child of 1:
3
Enter left child of 3:
-1
Enter right child of 3:
-1
```
输出结果为:
```
Inorder traversal: 2 1 3
Preorder traversal: 1 2 3
Postorder traversal: 2 3 1
```
阅读全文