续二叉搜索树递归玩法

文章目录


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

代码解读


相关推荐
疯狂打码的少年6 分钟前
【数据结构】交换类排序:冒泡与快速排序
数据结构·笔记·算法·排序算法
Nil20834 分钟前
leetcode 108有序数组转换为二叉搜索树
数据结构·算法·leetcode
高频因子挖掘机35 分钟前
QuantDash 成交量单位统一实战:从“手”到“股”的跨市场量化数据清洗全流程
后端·算法·github
程序员打怪兽38 分钟前
C++:类与对象,封装,继承,多态,构造/析构,重载/重写
c++
Escalating_xu1 小时前
【C++ STL简介】从六大组件到容器、迭代器与算法协作
java·c++·算法
Brilliantwxx1 小时前
【Linux】 进程(3)深度解析:从查看进程到进程状态
linux·服务器·网络·c++
啊啊啊啊啊!!!!1 小时前
【c++】二叉搜索树
开发语言·c++
ShineWinsu2 小时前
对于 C++:C++20中Concept(概念) 与 Coroutine(协程)的解析
linux·开发语言·网络·c++·c++20·epoll
纪念 2292 小时前
算法二叉树(一)
算法
liulilittle2 小时前
llmx 学习手册 06 —— CPU 指令集优化(AVX-512 三层演进)
c++·学习·算法·ai·llm