二叉排序树的操作

#include<cstdio>
#include<cstdlib>
#include<iostream>

using namespace std;

struct BTNode
{
	int data;
	BTNode* left;
	BTNode* right;
};
BTNode* FindMin(BTNode* pRoot);
BTNode* BSTSearch(BTNode* bt, int key)//查找
{
	if (bt == NULL)
		return NULL;
	else
	{
		if (bt->data == key)
			return bt;
		else if (bt->data < key)
			return BSTSearch(bt->right, key);
		else
			return BSTSearch(bt->left, key);
	}
}
int BSTInsert(BTNode* &bt, int key)//插入操作
{
	if (bt == NULL)
	{
		bt = new BTNode();
		bt->left = bt->right = NULL;
		bt->data = key;
		return 1;
	}
	else {
		if (bt->data == key)
			return 0;
		else if (key < bt->data)
			return BSTInsert(bt->left, key);
		else
			return BSTInsert(bt->right, key);
	}
}
void CreateBST(BTNode* &bt, int key[], int n)//创建二叉排序树
{
	int i;
	bt = NULL;
	for (i = 0; i < n; ++i)
		BSTInsert(bt, key[i]);
}
void Inoeder(BTNode* pRoot)//中序遍历
{
	if (pRoot == NULL)
		return;
	Inoeder(pRoot->left);
	printf("%d ", pRoot->data);
	Inoeder(pRoot->right);
}

void Delete(BTNode* &pNode)//删除节点pNode
{
	BTNode*q = NULL, *s=NULL;
	if (pNode->right == NULL)
	{
		q = pNode;
		pNode = pNode->left;
		free(q);
	}
	else if(pNode->left==NULL)
	{
		q = pNode;
		pNode = pNode->right;
		free(q);
	}
	else
	{
		q = pNode;
		s = pNode->left;
		while (s->right)
		{
			q = s;
			s = s->right;
		}
		pNode->data = s->data;
		if (q != pNode)
			q->right = s->left;
		else
			q->left = s->left;
		free(s);
	}
	
}
int DeleteNode(BTNode* &pRoot, int key)//删除关键字key的节点
{
	if (pRoot == NULL)
		return 0;
	else
	{
		if (key == pRoot->data)
			Delete(pRoot);
		else if (key < pRoot->data)
			DeleteNode(pRoot->left, key);
		else
			DeleteNode(pRoot->right, key);

	}
}


BTNode* FindMin(BTNode* pRoot)
{
	if (pRoot == NULL)
		return NULL;
	while (pRoot->left)
	{
		pRoot = pRoot->left;
	}
	return pRoot;
}
BTNode* FindMax(BTNode* pRoot)
{
	if (pRoot == NULL)
		return NULL;
	while (pRoot->right)
	{
		pRoot = pRoot->right;
	}
	return pRoot;
}
int main()
{
	int data[10] = { 62,88,58,47,35,73,51,99,37,93 };
	BTNode* pRoot = NULL;
	CreateBST(pRoot, data, 10);
	Inoeder(pRoot);
	printf("\n");
	
	//Delete(pRoot, 51);
	DeleteNode(pRoot, 35);
	Inoeder(pRoot);
	cout << endl;
	//cout << FindMax(pRoot)->data << endl;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值