续二叉搜索树递归玩法

文章目录


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

代码解读


相关推荐
Tiny番茄4 分钟前
LeetCode 93.复原IP地址 LeetCode 78.子集 LeetCode 90.子集II
算法·leetcode·职场和发展
SylviaW086 分钟前
python-leetcode 69.最小栈
数据结构·算法·leetcode
飞川撸码7 分钟前
【LeetCode 热题100】搜索旋转排序数组(力扣33 / 81/ 153/154)(Go语言版)
数据结构·算法·leetcode·golang
知识漫步41 分钟前
代码随想录算法训练营第60期第四十二天打卡
算法
叒卮1 小时前
小白编程学习之巧解「消失的数字」
数据结构·学习·算法
噜噜噜噜鲁先森1 小时前
MVDR源码(可直接运行)
算法·matlab·信号处理·阵列信号处理·声源定位算法
felix_fang_xin1 小时前
FIR数字滤波器设计与实现
人工智能·算法
愚润求学1 小时前
【Linux】进程间通信(三):命名管道
linux·运维·服务器·开发语言·c++·笔记
一匹电信狗2 小时前
【数据结构】队列的完整实现
c语言·数据结构·c++·算法·leetcode·排序算法·visual studio