C++——二叉查找树的创建与查找

二叉排序、查找树:
1、用随机函数生成10个待排序元素;
2、利用二叉查找树输出升序序列;
3、利用同一棵二叉查找树输出降序序列;
4、写出查找的递归函数;

#include
#include
using namespace std;

typedef int ElemType;
typedef struct BinarySortTreeNode
{
	ElemType data;
	struct BinarySortTreeNode *lchild, *rchild;
}BinarySortTreeNode,*BinarySortTree;

int random[10];         //random数组用来存储随机数
void GetTenRand()       //得到十个随机数
{
	srand(signed(time(0)));
	for (int i = 0; i < 10; i++)
	{
		random[i] = rand() % 100; //使用随机函数得到十个数
	}
}

void InsertBSTree(BinarySortTree &T,ElemType e)//插入结点
{
	if (T == NULL)
	{
		BinarySortTree S;
		S = new BinarySortTreeNode;
		S->data = e;
		S->lchild = S->rchild = NULL;
		T = S;
	}
	else if (e < T->data)
		InsertBSTree(T->lchild, e);
	else InsertBSTree(T->rchild, e);//把相等的情况放在右子树
}

BinarySortTree SearchBSTree(BinarySortTree T, ElemType e)//递归查找函数
{
	if ((!T) || e == T->data) return T;
	else if (e < T->data) return SearchBSTree(T->lchild,e);
	else return SearchBSTree(T->rchild,e);
}

void CreateBSTree(BinarySortTree &T)//利用建立的随机数组创建二叉查找树
{
	T = NULL;
	for (int i = 0; i < 10; i++)
	{
		InsertBSTree(T, random[i]);
	}
}

/*void CreateBSTree(BinarySortTree &T)//创建二叉查找树
{
	T = NULL;//初始化置空
	ElemType e;  
	cout << "请输入需要插入的数据:";
		cin >> e;
	while (e != 0)//以0作为结束标志
	{
		InsertBSTree(T, e);
		cin >> e;
	}
}*/

void  AscendingPrintBSTree(BinarySortTree T)//中序升序打印二叉查找树
{
	if (T)
	{
		AscendingPrintBSTree(T->lchild);
		cout << T->data<<" ";
		AscendingPrintBSTree(T->rchild);
	}
}

void DescendingPrintBSTree(BinarySortTree T)//中序降序打印二叉查找树
{
	if (T)
	{
		DescendingPrintBSTree(T->rchild);
		cout << T->data<<" ";
		DescendingPrintBSTree(T->lchild);
	}
}

int main(void)
{
	BinarySortTree T=NULL;
	GetTenRand();        //获取十个随机数
	CreateBSTree(T);     //创建二叉查找树
	cout << "升序打印:";
	AscendingPrintBSTree(T);
	cout << endl;
	cout << "降序打印:";
	DescendingPrintBSTree(T);
	cout << endl;
	system("pause");
}

你可能感兴趣的:(C++——二叉查找树的创建与查找)