续二叉搜索树递归玩法

文章目录


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

代码解读


相关推荐
Mr_Xuhhh25 分钟前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水29 分钟前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
南境十里·墨染春水1 小时前
C++ 笔记 友元(面向对象)
开发语言·c++·笔记
C++ 老炮儿的技术栈2 小时前
分享一个安全的CString
c语言·c++·windows·git·安全·visual studio
穿条秋裤到处跑2 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
桦02 小时前
[C++复习]:STL
开发语言·c++
苏宸啊3 小时前
rbtree封装map和set
c++
汉克老师3 小时前
GESP2025年6月认证C++三级( 第一部分选择题(1-8))
c++·二进制·原码·补码·gesp三级·gesp3级·八进制、
不想写代码的星星3 小时前
C++ 折叠表达式:“我写递归你写折叠,咱俩代码差十年”
c++
CoovallyAIHub4 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github