续二叉搜索树递归玩法

文章目录


先赞后看,养成习惯!!!^ _ ^<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;
	}

代码解读


相关推荐
有梦想的骇客2 小时前
书籍将正方形矩阵顺时针转动90°(8)0605
线性代数·算法·矩阵
有梦想的骇客2 小时前
书籍“之“字形打印矩阵(8)0609
java·算法·矩阵
Chenyu_3102 小时前
12.找到字符串中所有字母异位词
c语言·数据结构·算法·哈希算法
苏三福2 小时前
yolo11-seg ultralytics 部署版本
算法·yolo11
achene_ql4 小时前
select、poll、epoll 与 Reactor 模式
linux·服务器·网络·c++
SY师弟5 小时前
51单片机——计分器
c语言·c++·单片机·嵌入式硬件·51单片机·嵌入式
wuqingshun3141595 小时前
蓝桥杯 冶炼金属
算法·职场和发展·蓝桥杯
豪斯有话说6 小时前
C++_哈希表
数据结构·c++·散列表
jndingxin7 小时前
OpenCV CUDA模块光流计算-----实现Farneback光流算法的类cv::cuda::FarnebackOpticalFlow
人工智能·opencv·算法