#include<stdio.h> #include<string.h> #include<malloc.h> typedef struct node { int key; struct node *lchild,*rchild; }BSTNode,*BSTree; //二叉排序树插入 void InsertBST(BSTree *bst,int key) { BSTree s; if(*bst==NULL) { s=(BSTree)malloc(sizeof(BSTNode)); s->key=key; s->lchild=NULL; s->rchild=NULL; *bst=s; } } //创建二叉排序树 void CreatBST(BSTree *bst) { int key; *bst=NULL; scanf("%d",&key); while(key!=ENDKEY) { InsertBST(bst,key); scanf("%d",&key); } }填写该代码 使其实现用二叉链表作为存储结构,输入键值序列建立一棵二叉排序树,然后中序遍历这棵二叉树。的功能
时间: 2024-03-07 14:47:58 浏览: 30
以下是完整代码:
```c
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define ENDKEY -1
typedef struct node {
int key;
struct node *lchild, *rchild;
} BSTNode, *BSTree;
// 二叉排序树插入
void InsertBST(BSTree *bst, int key) {
BSTree s, p, q;
s = (BSTree)malloc(sizeof(BSTNode));
s->key = key;
s->lchild = s->rchild = NULL;
if (*bst == NULL) {
*bst = s;
} else {
p = *bst;
while (p != NULL) {
q = p;
if (key < p->key) {
p = p->lchild;
} else {
p = p->rchild;
}
}
if (key < q->key) {
q->lchild = s;
} else {
q->rchild = s;
}
}
}
// 创建二叉排序树
void CreatBST(BSTree *bst) {
int key;
*bst = NULL;
scanf("%d", &key);
while (key != ENDKEY) {
InsertBST(bst, key);
scanf("%d", &key);
}
}
// 中序遍历二叉树
void InOrder(BSTree bst) {
if (bst != NULL) {
InOrder(bst->lchild);
printf("%d ", bst->key);
InOrder(bst->rchild);
}
}
int main() {
BSTree bst;
CreatBST(&bst);
InOrder(bst);
return 0;
}
```
该代码使用二叉链表作为存储结构,实现了输入键值序列建立一棵二叉排序树,并且中序遍历输出二叉树。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)