二叉查找树精华修改版实现

二叉查找树精华修改版实现

实现功能如下

  1. 置空树功能
  2. 查找功能
  3. 查找最小值功能
  4. 查找最大值功能
  5. 插入功能
  6. 删除功能
  7. 层序遍历功能(BFS)
  8. 等等。。。。可以自己进行添加

代码实现如下

#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

struct BinSeaTree;
struct ElementType;
typedef struct BinSeaTree* BST;

int pd = 0;//非常重要!添加节点时,判断该树是否为空树

struct ElementType {
	int data;
};

struct BinSeaTree {
	ElementType key;
	BST Left;
	BST Right;
};

BST Init(BST& b) {
	b = new BinSeaTree();
	b->Left = NULL;
	b->Right = NULL;
	return b;
}

void MakeEmpty(BST b) {
	if (b) {
		MakeEmpty(b->Left);
		MakeEmpty(b->Right);
		delete b;
	}
}

BST Find(ElementType x , BST b) {
	if (!b) return NULL;
	if (x.data == b->key.data) return b;
	else if (x.data < b->key.data) Find(x, b->Left);
	else if (x.data > b->key.data) Find(x, b->Right);
}

BST FindMin(BST b) {
	if (!b->Left) return b;
	else FindMin(b->Left);
}

BST FindMax(BST b) {
	if (!b->Right) return b;
	else FindMax(b->Right);
}

BST Insert(ElementType x, BST b) {
	if (pd == 0) {
		pd = 1;
		b->key = x;
		return NULL;
	}
	if (!b) {
		BST newNode = new BinSeaTree();
		newNode->key = x;
		newNode->Left = NULL;
		newNode->Right = NULL;
		b = newNode;
	}
	else {
		if (x.data < b->key.data) b->Left = Insert(x, b->Left);
		else if (x.data > b->key.data) b->Right = Insert(x, b->Right);
	}
	return b;
}

BST Delete(ElementType x, BST b) {
	if (x.data < b->key.data) b->Left = Delete(x, b->Left);
	else if (x.data > b->key.data) b->Right = Delete(x, b->Right);
	else {
		if (b->Left && b->Right) {
			BST temp;
			temp = FindMin(b->Right);
			b->key = temp->key;
			b->Right = Delete(temp->key, b->Right);
		}
		else {
			BST temp;
			temp = b;
			if (b->Left == NULL) b = b->Right;
			else if (b->Right == NULL) b = b->Left;
			delete temp;	
		}
	}
	return b;
}

void Display(BST b) {
	queue<BST> que;
	BST temp = new BinSeaTree();
	temp = b;
	que.push(temp);
	while (temp) {
		if (temp->Left) que.push(temp->Left);
		if (temp->Right) que.push(temp->Right);
		cout << que.front()->key.data << endl;
		que.pop();
		if (que.empty()) return;
		temp = que.front();
	}
}

int main() {
	BST b;
	b = Init(b);
	ElementType a, s, d, f, g, h, j, k, l;
	a.data = 10;
	s.data = 7;
	d.data = 15;
	f.data = 8;
	g.data = 4;
	h.data = 9;
	j.data = 14;
	k.data = 20;
	l.data = 17;
	Insert(a, b);
	Insert(s, b);
	Insert(d, b);
	Insert(f, b);
	Insert(g, b);
	Insert(h, b);
	Insert(j, b);
	Insert(k, b);
	Insert(l, b);

	Display(b);
	cout << endl;

	//BST e=FindMin(b->Right);
	//cout << e->key.data << endl;
	//e = FindMax(b->Right);
	//cout << e->key.data << endl;
	
	//Delete(l, b);
	//Display(b);
	//cout << endl;

	return 0;
}

欢迎大家审阅😄

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值