由多种化妆品品牌价格组成的二叉排序树(数据结构C语言版)

实验二 树的应用 (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文件

/**
 *BST (binary_sort_tree)
 *data: 2019/10/31
 *liu kai
 */

#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);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值