《大話數據結構》C++實現二叉排序樹的查找、插入和刪除操作

#include<iostream>

using namespace std;

typedef int status;

//定義一個樹的結構體
typedef struct BiTNode
{
	int data;
	struct BiTNode* lchild, * rchild;
}BiTNode, * BiTree;

//函數聲明
void CreateBST(BiTree* T, int a[], int n);
void outputBST(BiTree T);
status InsertBST(BiTree* T, int key);
status DeleteBST(BiTree*T,int key);
status Delete(BiTree *p);

//二叉排序樹的查找函數定義
status SearchBST(BiTree T,int key,BiTree f,BiTree *p)
{
	if (!T)
	{
		*p = f;
		return false;
	}
	else if (key==T->data)
	{
		*p = T;
		return true;
	}
	else if (key<T->data)
	{
		return SearchBST(T->lchild,key,T,p);
	}
	else
	{
		return SearchBST(T->rchild,key,T,p);
	}
}

//二叉排序樹的插入函數定義
status InsertBST(BiTree *T,int key)
{
	BiTree p=NULL, s=NULL;
	if (!SearchBST(*T,key,NULL,&p))
	{
		s = (BiTree)malloc(sizeof(BiTNode));
		s->data = key;
		s->lchild = s->rchild = NULL;
		if (!p)
			* T = s;
		else if (key < p->data)
			p->lchild = s;
		else
			p->rchild = s;
		return true;
	}
	return false;
}

//二叉排序樹的刪除操作函數定義
status DeleteBST(BiTree* T, int key)
{
	if (!*T)
		return false;
	else
	{
		if (key == (*T)->data)
		{
			return Delete(T);
		}
		else if (key<(*T)->data)
		{
			return DeleteBST(&(*T)->lchild,key);
		}
		else
		{
			return DeleteBST(&(*T)->rchild,key);
		}
	}
}

//根據節點的三種情況來刪除節點
status Delete(BiTree* p)
{
	BiTree q, s;
	if ((*p)->rchild==NULL)
	{
		q = *p; *p = (*p)->lchild; free(q);
	}
	else if ((*p)->lchild==NULL)
	{
		q = *p; *p = (*p)->rchild; free(q);
	}
	else
	{
		q = *p; s = (*p)->lchild;
		while (s->rchild)
		{
			q = s; s = s->rchild;
		}
		(*p)->data = s->data;
		if (q != *p)
			q->rchild = s->lchild;
		else
			q->lchild = s->lchild;
		free(s);
	}
	return true;
}

//通過一個數組來創建二叉排序樹
void CreateBST(BiTree*T, int a[], int n)
{
	int i;
	for (i = 0; i < n; i++)
	{
		InsertBST(T, a[i]);
	}
}

//把一個二叉排序樹中序遍歷打印
void outputBST(BiTree T)
{
	if (T == NULL)
	{
		return;
	}
	outputBST(T->lchild);
	cout << T->data << " ";
	outputBST(T->rchild);
}

//主函數
int main()
{
	int a[] = { 62,88,58,47,35,73,51,99,37,93 };
	BiTree T = NULL;

	//創建二叉排序樹
	CreateBST(&T, a, 10);

	//在二叉排序樹中插入95
	InsertBST(&T, 95);

	//在二叉排序樹中查找節點
	int b = 95;
	BiTree p = NULL;
	if (!SearchBST(T, b, NULL, &p))
		cout << "沒有找到" << endl;
	else
	{
		cout << b << "查找結果的指針爲:\n" << p << endl;
	}

	//在二叉排序樹中刪除88節點
	DeleteBST(&T, 88);

	//驗證上述的插入和刪除操作
	outputBST(T);
	cout << endl;

	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章