c语言代码实现二叉链表作为存储结构,输入键值序列建立一棵二叉排序树,然后中序遍历这棵二叉树。
时间: 2024-05-05 15:21:37 浏览: 158
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
int key;
struct _node* left;
struct _node* right;
} Node;
Node* create_node(int key) {
Node* node = (Node*)malloc(sizeof(Node));
node->key = key;
node->left = NULL;
node->right = NULL;
return node;
}
void insert(Node** root, int key) {
if (*root == NULL) {
*root = create_node(key);
return;
}
if (key < (*root)->key) {
insert(&((*root)->left), key);
} else {
insert(&((*root)->right), key);
}
}
void inorder_traversal(Node* root) {
if (root == NULL) {
return;
}
inorder_traversal(root->left);
printf("%d ", root->key);
inorder_traversal(root->right);
}
int main() {
Node* root = NULL;
int n, key;
printf("Enter the number of keys: ");
scanf("%d", &n);
printf("Enter the keys: ");
for (int i = 0; i < n; i++) {
scanf("%d", &key);
insert(&root, key);
}
printf("Inorder traversal: ");
inorder_traversal(root);
printf("\n");
return 0;
}
```
输入示例:
```
Enter the number of keys: 7
Enter the keys: 3 1 4 1 5 9 2
```
输出示例:
```
Inorder traversal: 1 1 2 3 4 5 9
```
阅读全文