编写c语言,以二叉链表作存储结构,建立一颗二叉树,输出该二叉树的中序遍历序列
时间: 2024-01-23 18:42:38 浏览: 93
以下是C语言代码,采用二叉链表实现二叉树,并输出中序遍历序列:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
typedef struct TreeNode TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return createNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
void inorder(TreeNode* root) {
if (root == NULL) {
return;
}
inorder(root->left);
printf("%d ", root->val);
inorder(root->right);
}
int main() {
TreeNode* root = NULL;
int n, val;
printf("Enter the number of nodes: ");
scanf("%d", &n);
printf("Enter the values of the nodes: ");
for (int i = 0; i < n; i++) {
scanf("%d", &val);
root = insert(root, val);
}
printf("Inorder traversal: ");
inorder(root);
printf("\n");
return 0;
}
```
输入格式如下:
```
Enter the number of nodes: 7
Enter the values of the nodes: 4 2 5 1 6 3 7
```
输出结果如下:
```
Inorder traversal: 1 2 3 4 5 6 7
```
阅读全文