续二叉搜索树递归玩法

文章目录


先赞后看,养成习惯!!!^ _ ^<3 ❤️ ❤️ ❤️
码字不易,大家的支持就是我坚持下去的动力。点赞后不要忘了关注我哦!
所属专栏:C++进阶

一、插入递归

cpp 复制代码
	bool _InsertR(const K& key)
	{
		return _Insert(_root, key);
	}
bool _Insert(Node*& root, const K& key)
{
	if (root == nullptr)
	{
		root = new Node(key);
	}
	if (root->_key > key)
	{
		return _Insert(root->left, key);
	}
	else if (root->_key < key)
	{
		return _Insert(root->right, key);
	}
	else
	{
		return false;
	}
}

代码解读

二、寻找递归(非常简单,走流程就行)

cpp 复制代码
	bool _FindR(const K& key)
	{
		return _Find(_root, key);
	}
	bool _Find(Node* root, const K& key)
{
	if (root == nullptr)
		return false;
	if (root->_key > key)
	{
		return _Find(root->left,key);
	}
	else if (root->_key < key)
	{
		return _Find(root->right,key);
	}
	else
	{
		return true;
	}
}

三、插入递归(理解起来比较麻烦)

cpp 复制代码
	bool _EraseR(const K& key)
	{
		return _Erase(_root, key);
	}
	bool _Erase(Node*& root, const K& key)
{
	if (root == nullptr)
		return false;
	if (root->_key > key)
	{
		return _Erase(root->left, key);
	}
	else if (root->_key < key)
	{
		return _Erase(root->right, key);
	}
	else
	{
		Node* del = root;
		if (root->left == nullptr)
		{
			root = root->right;
		}
		else if (root->right == nullptr)
		{
			root = root->left;
		}
		//递归转化到子树去删除
		else
		{
			Node* leftmax = root->left;
			while (leftmax->right)
			{
				leftmax = leftmax->right;
			}

			swap(root->_key, leftmax->_key);

			return _Erase(root->left, key);
		

		}
		delete del;
		return true;
	}

代码解读


相关推荐
Σίσυφος19003 分钟前
Halcon中霍夫直线案例
算法
fyzy13 分钟前
C++写后端实现,实现前后端分离
开发语言·c++
Anastasiozzzz30 分钟前
leetcode力扣hot100困难题--4.俩个正序数列的中位数
java·算法·leetcode·面试·职场和发展
CSDN_RTKLIB39 分钟前
C++谓词
c++·stl
BHXDML1 小时前
第六章:推荐算法
算法·机器学习·推荐算法
Tisfy1 小时前
LeetCode 3510.移除最小数对使数组有序 II:有序集合
算法·leetcode·题解·设计·有序集合
汉克老师2 小时前
GESP2025年9月认证C++五级真题与解析(单选题9-15)
c++·算法·贪心算法·排序算法·归并排序·gesp5级·gesp五级
飞鹰512 小时前
CUDA高级优化实战:Stream、特殊内存与卷积优化—Week3学习总结
c++·gpt·chatgpt·gpu算力
lihao lihao2 小时前
c++红黑树
算法
Sarvartha2 小时前
递推与递归笔记
算法