建立二叉排序树

编写算法,输入一组整数,以9999为结束标志,将这些数据建立二叉排序树。输出中序排序序列检验是否为二叉排序树,并且在二叉排序树内查找值。

#include<iostream>
using namespace std;
struct BiNode
{
	int key;
	int data;
	BiNode* lchild, * rchild;

};
class BiSortTree
{
	BiNode* root;
	void Insert(BiNode*& ptr, int k);
	BiNode* Search(BiNode* ptr, int k);
	void Free(BiNode* ptr);
	//void PreOrder(BiNode* p);
	void InOrder(BiNode* p);
	//int judgeBST(BiNode* bt);

public:
	BiSortTree();
	BiSortTree(int a[], int n);
	~BiSortTree();
	void Insert(int k);
	bool Search2(int k);
	//void PreOrder();
	void InOrder();

	//int judgeBST();
};
BiSortTree::BiSortTree()
{
	root = NULL;
}
BiSortTree::BiSortTree(int a[], int n)//二叉排序树的建立
{
	root = NULL;
	for (int i = 0; i < n; i++)
	{
		Insert(root, a[i]);
	}
}
void BiSortTree::InOrder(BiNode* ptr)
{
	if (ptr == NULL)
		return;
	//PreOrder(ptr->lchild);
	InOrder(ptr->lchild);

	cout << ptr->key << " ";
	//PreOrder(ptr->rchild);

	InOrder(ptr->rchild);
}

void BiSortTree::InOrder()
{
	InOrder(root);
}
BiNode* BiSortTree::Search(BiNode* ptr, int k)//二叉排序树的查找
{
	while (ptr)
	{
		if (k == ptr->key)
		{
			return ptr;
		}
		else if (k < ptr->key)
			ptr = ptr->lchild;
		else
			ptr = ptr->rchild;
	}
	return NULL;
}
bool BiSortTree::Search2(int k)
{
	return Search(root, k) != NULL;
}
void BiSortTree::Insert(BiNode*& ptr, int k)//二叉排序树的插入
{
	if (ptr == NULL)
	{
		ptr = new BiNode;
		ptr->key = k;
		ptr->lchild = ptr->rchild = NULL;
	}
	else
	{
		if (k < ptr->key)
			Insert(ptr->lchild, k);
		else
			if (k > ptr->key)
				Insert(ptr->rchild, k);
	}

}
void BiSortTree::Insert(int k)
{
	Insert(root, k);
}


void BiSortTree::Free(BiNode* ptr)//二叉排序树的析构
{
	if (ptr == NULL)
		return;
	Free(ptr->lchild);
	Free(ptr->rchild);
	delete ptr;

}

BiSortTree::~BiSortTree()
{
	Free(root);
}
int main()
{
	int i=0;
	int a[100];	
	cout << endl << "请输入序列值,以9999为结束标志: ";
	while (1)
	{
		cin >> a[i];
		if (a[i] == 9999)
			break;
		else
			i++;

	}
	int n;
	cout << "请输入这个二叉排序树序列的个数: "; 
	cin >> n;
	cout << endl;
	BiSortTree t(a, n);
	cout << "请输出中序遍历序列: ";
	t.InOrder();
	cout << endl;
	int item;
	cout << endl << "二叉排序树的查找,请输入要查找的值item: ";
	cin >> item;
	if (t.Search2(item))
		cout << endl << "是否找到: " << "找到啦";
	else
		cout << endl << "是否找到: " << "没找到";
	return 0;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值