数据结构学习笔记 --- 二叉搜索树

本文详细介绍了二叉搜索树(BST)的数据结构,包括其节点特性,以及如何实现查找、插入和删除节点的操作,重点展示了递归和非递归方法的应用。
摘要由CSDN通过智能技术生成

二叉搜索树

二叉搜索树(binary search tree)满足以下条件。

  1. 对于根节点,左子树中所有节点的值 (<) 根节点的值 (<) 右子树中所有节点的值。
  2. 任意节点的左、右子树也是二叉搜索树,即同样满足条件1。
查找节点
void BinaryTree::search(int num)
{
	bool flag = false;
	TreeNode* current = root;
	while (current!=nullptr)
	{
		if (current->val < num)
			current = current->right;
		else if (current->val > num)
			current = current->left;
		else flag = true;
	}

	if (flag) cout << "找到了";
	else cout << "未找到";
}
插入节点
void BinaryTree::insert(int val)
{
	if (root == nullptr) {
		root = new TreeNode(val);
		return;
	}
	TreeNode* current = root;
	TreeNode* parent = nullptr;

	//我们使用循环而不是递归来找到要插入的位置,并且根据val的值来判断是插入到左子树还是右子树。这样就避免了无限递归的问题。
	while (current != nullptr) {
		parent = current;
		if (val < current->val) {
			current = current->left;
		}
		else {
			current = current->right;
		}
	}

	if (val < parent->val) {
		parent->left = new TreeNode(val);
	}
	else {
		parent->right = new TreeNode(val);
	}
}
删除结点
void BinaryTree::deleteNode(int val)
{
	if (root == nullptr) return;
	TreeNode* current = root;
	TreeNode* parent = nullptr;

	while (current != nullptr) {
		if (current->val == val)
			break;
		parent = current;
		if (val < current->val) {
			current = current->left;
		}
		else {
			current = current->right;
		}
	}

	// 若无待删除节点,则直接返回
	if (current == nullptr)
		return;
	// 子节点数量 = 0 or 1
	if (current->left == nullptr || current->right == nullptr) {
		// 当子节点数量 = 0 / 1 时, child = nullptr / 该子节点
		TreeNode* child = current->left != nullptr ? current->left : current->right;
		// 删除节点 current
		if (current != root) {
			if (parent->left == current)
				parent->left = child;
			else
				parent->right = child;
		}
		else {
			// 若删除节点为根节点,则重新指定根节点
			root = child;
		}
		// 释放内存
		delete current;
	}
	// 子节点数量 = 2
	else {
		// 获取中序遍历中 current 的下一个节点
		TreeNode* tmp = current->right;
		while (tmp->left != nullptr) {
			tmp = tmp->left;
		}
		int tmpVal = tmp->val;
		// 递归删除节点 tmp
		deleteNode(tmp->val);
		// 用 tmp 覆盖 current
		current->val = tmpVal;
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值