/**
* 实验题目:
* 由有序序列创建一颗高度最小的二叉排序树
* 实验目的:
* 掌握二叉排序树的构造过程及其算法设计
* 实验内容:
* 设计程序,对于给定的一个有序的关键字序列,创建一颗高度
* 最小的二叉排序树。
* 解决思路:
* 要创建一颗高度最小的二叉排序树,就必须让左右子树的结点
* 个数越接近越好。由于给定的是一个关键字有序序列a[start...end],
* 所以让其中间位置的关键字a[mid]作为根结点,左序列a[start...mid-1]
* 构造左子树,右序列a[mid+1...end]构造右子树。
*/
#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
#define MAX_SIZE 100
typedef int key_type; // 定义关键字类型
typedef char info_type;
typedef struct node { // 记录类型
key_type key; // 关键字项
info_type data; // 其他数据域
struct node *lchild; // 左孩子指针
struct node *rchild; // 右孩子指针
}BSTNode;
/*----------------以括号表示法输出二叉排序树bt------------------*/
void disp_bst(BSTNode *bt); // 函数声明
bool insert_bst(BSTNode *&bt, key_type key) // 在以bt为根结点的BST中插入一个关键字为key的结点
{
if(bt == NULL) // 原树为空,新插入的记录为根结点
{
bt = (BSTNode *)malloc(sizeof(BSTNode));
bt->key = key;
bt->lchild = bt->rchild = NULL;
return true;
}
else if(key == bt->key)
return false;
else if(key < bt->key)
return insert_bst(bt->lchild, key); // 插入到bt结点的左子树中
else
return insert_bst(bt->rchild, key); // 插入到bt结点的右子树中
}
/*----------------由数组a中的关键字建立一颗二叉排序树------------------*/
BSTNode *create_bst(key_type a[], int n)
{
BSTNode *bt = NULL; // 初始时bt为空树
int i = 0;
while(i < n)
{
if(insert_bst(bt, a[i]) == 1)