二叉查找树BST的删除操作

二叉查找树BST的删除操作(哈工大版)

C++代码

/***** 二叉查找树BST *****/
#include<iostream>
using namespace std;


struct BST {   //BST = Binary Search Tree
	int data;
	BST* lchild, * rchild;
};


/***函数声明***/
void Insert(int data, BST*& tree);
BST* Create();
BST* Search(int key, BST* tree);
void Delete(int key, BST*& tree);
int Deletemin(BST*& tree);
void Inorder(BST* tree);


void Insert(int data, BST*& tree) {   //巧用引用
	if (tree == NULL) {
		tree = new BST;
		tree->data = data;
		tree->lchild = NULL;
		tree->rchild = NULL;
	}
	else if (data < tree->data)  Insert(data, tree->lchild);
	else if (data > tree->data)  Insert(data, tree->rchild);
}
BST* Create() {
	BST* tree = NULL;
	int data;
	cin >> data;
	while (data) {   //假设输入0结束
		Insert(data, tree);
		cin >> data;
	}
	return tree;
}
BST* Search(int key, BST* tree) {
	BST* p = tree;
	if (p == NULL || p->data == key)  return p;
	else if (key < p->data)  return Search(key, p->lchild);
	else  return Search(key, p->rchild);
}
void Delete(int key, BST*& tree) {   //删除二叉树的某个节点值
	if (tree != NULL) {
		if (key < tree->data)
			Delete(key, tree->lchild);
		else if (key > tree->data)
			Delete(key, tree->rchild);
		else if (tree->lchild == NULL)
			tree = tree->rchild;
		else if (tree->rchild == NULL)
			tree = tree->lchild;
		else  tree->data = Deletemin(tree->rchild);
	}
}
int Deletemin(BST*& tree) {
	int temp;
	BST* p;
	if (tree->lchild == NULL) {
		temp = tree->data;
		p = tree;
		tree = tree->rchild;
		delete p;
		return temp;
	}
	else  return Deletemin(tree->lchild);
}
void Inorder(BST* tree) {
	if (tree != NULL) {
		Inorder(tree->lchild);
		cout << tree->data << " ";
		Inorder(tree->rchild);
	}
}
int main() {
	BST* tree = Create();
	Inorder(tree);   //中序遍历以查看排序结果
	cout << endl;
	int key;
	cin >> key;   //输入查找并删除的匹配值
	BST* p = Search(key, tree);
	if (p == NULL)
		cout << "未找到该值!" << endl;
	else  cout << "已搜索到:" << p->data << endl;   //输出查找到的值
	Delete(key, tree);
	Inorder(tree);   //中序遍历以查看删除结果
	return 0;
}

测试样例

样例1

输入:

5 1 2 4 3 7 9 6 8 0

输出:

1 2 3 4 5 6 7 8 9

继续输入查找并删除的匹配值:

9

输出:

已搜索到:9
1 2 3 4 5 6 7 8

样例2

输入:

5 1 2 4 3 7 9 6 8 0

输出:

1 2 3 4 5 6 7 8 9

继续输入查找并删除的匹配值:

10

输出:

未找到该值!
1 2 3 4 5 6 7 8 9

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

M_blueberry

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值