实验二 树的应用 (2学时)
1、实验内容
建立一个由多种化妆品品牌价格组成的二叉排序树,并按照价格从低到高的顺序 打印输出。
2、实验目的
通过本实验掌握二叉排序树的建立和排序算法,了解二叉排序树在实际中的应用并熟练运用二叉排序树解决实际问题。
3、实验要求
(1)创建化妆品信息的结构体; (2)定义二叉排序树链表的结点结构; (3)依次输入各类化妆品品牌的价格并按二叉排序树的要求创建一个二叉排序树链表; (4)对二叉排序树进行中序遍历输出,打印按价格从低到高顺序排列的化妆品品牌信息。
[注] 这次是用的Visual studio的mscv编译器写的…
myhead.h文件
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "database.c"
BinTree
* CreateBST(BinTree
* tree
, Info
* myinfo
, int sum
);
BinTree
* InsertBST(BinTree
* t
, Info key
);
void inorder(BinTree
* tree
);
database.c文件
#define MAX_STRING 100
#define MAX_INFO 100
typedef struct {
char brand
[MAX_STRING
];
int price
;
}Info
;
typedef struct Fnode
{
Info info
;
struct node
* lchild
, * rchild
;
}BinTree
;
main.c文件
#include "myhead.h"
int main(int args
, char* argv
[]) {
BinTree
*tree
= NULL;
int sum
;
Info myinfo
[MAX_INFO
];
printf("input sum:");
scanf_s("%d", &sum
);
printf("input brand & price:\n");
for (int i
= 0; i
< sum
; i
++) {
for (int j
= 0; j
< MAX_STRING
; j
++) {
myinfo
[i
].brand
[j
] = '\0';
}
scanf_s("%s", myinfo
[i
].brand
, MAX_STRING
);
scanf_s("%d", &myinfo
[i
].price
);
}
tree
= CreateBST(tree
, myinfo
, sum
);
printf("output\n");
inorder(tree
);
return 0;
}
BinTree
* CreateBST(BinTree
*tree
, Info
* myinfo
, int sum
) {
for (int i
= 0; i
< sum
; i
++)
tree
= InsertBST(tree
, myinfo
[i
]);
return tree
;
}
BinTree
* InsertBST(BinTree
* t
, Info key
)
{
if (t
== NULL)
{
t
= (BinTree
*)malloc(sizeof(BinTree
));
if (t
) {
t
->lchild
= t
->rchild
= NULL;
strcpy_s(t
->info
.brand
, MAX_STRING
, key
.brand
);
t
->info
.price
= key
.price
;
}
else {
exit(1);
}
return t
;
}
if (key
.price
<= t
->info
.price
)
t
->lchild
= InsertBST(t
->lchild
, key
);
else
t
->rchild
= InsertBST(t
->rchild
, key
);
return t
;
}
void inorder(BinTree
*tree
) {
if (tree
) {
inorder(tree
->lchild
);
printf("brand:%s price:%d\n", tree
->info
.brand
, tree
->info
.price
);
inorder(tree
->rchild
);
}
}