爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      【数据结构】二叉搜索树BSTree

      首页 知识中心 数据库 文章详情页

      【数据结构】二叉搜索树BSTree

      2024-09-25 10:15:15 阅读次数:77

      c++

      一、概念

      二叉搜索树又称二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树:

      若它的左子树不为空,则左子树上所有节点的值都小于根节点的值

      若它的右子树不为空,则右子树上所有节点的值都大于根节点的值

      左<根<右

      它的左右子树也分别为二叉搜索树

      之所以又叫二叉排序树,是因为二叉搜索树中序遍历的结果是有序的

      【数据结构】二叉搜索树BSTree


      二、基础操作

      1.查找find

      基于二叉搜索树的特点,查找一个数并不难,若根节点不为空的情况下:

      若根节点key==查找key,直接返回true

      若根节点key>查找key,那得找到更小的,则往左子树查找

      若根节点key<查找key,那得找到更大的,则往右子树查找

      最多查找高度次,走到空为止,如果还没找到,则说明这个值不存在,返回false

      	bool find(const K& key)
      	{
      		Node* cur = _root;
      		while (cur)
      		{
      			if (cur->_key < key)
      			{
      				cur = cur->_right;
      			}
      			else if (cur->_key > key)
      			{
      				cur = cur->_left;
      			}
      			else
      			{
      				return true;
      			}
      		}
      		return false;
      	}
      

      2.插入Insert

      1.树为空,则直接插入,新增节点,直接插入root指针即可

      2.树不为空,按二叉搜索树性质查找插入位置,插入新节点。

      (注意:不能插入重复的元素,并且每次插入都是要定位到空节点的位置;我们先定义一个 cur从root开始,比较元素的大小:若插入的元素比当前位置元素小就往左走,比当前位置元素大就往右走,直到为空,相等就不能插入了;同时定义一个parent去记录当前 cur的前一个位置,最后判断cur是parent的左子树还是右子树即可)

      	bool Insert(const K& key)
      	{
      		if (_root == nullptr)
      		{
      			_root = new Node(key);
      			return true;
      		}
      		Node* parent = nullptr;
      		Node* cur = _root;
      		while (cur)
      		{
      			if (cur->_key < key)
      			{
      				parent = cur;
      				cur = cur->_right;
      			}
      			else if (cur->_key > key)
      			{
      				parent = cur;
      				cur = cur->_left;
      			}
      			else
      			{
      				return false;
      			}
      		}
      		cur = new Node(key);
      		if (parent->_key < key)
      		{
      			parent->_right = cur;
      		}
      		else
      		{
      			parent->_left = cur;
      		}
      		return true;
      	}
      

      3.中序遍历InOrder

      递归走起,同时由于_root是私有的,外部不能访问,我们可以在类内给中序提供一个方法即可,就不需要传参了

      void InOrder()
      	{
      		_InOrder(_root);
      		cout << endl;
      	}
      
      private:
      	void _InOrder(Node* root)
      	{
      		if (root == nullptr)
      		{
      			return;
      		}
      		_InOrder(root->_left);
      		cout << root->_key << " ";
      		_InOrder(root->_right);
      	}
      	Node* _root = nullptr;
      

      4.删除erase

      删除的情况比较多:

      1. 左右都为空:叶子结点,直接置空并链接到空指针
      2. 左为空或右为空:进行托孤:只有一个子节点,删除自己本身,并链接子节点和父节点(注意:如果父亲是空,也就是要删除根结点,此时根节点没有父亲,单独判断一下)
      3. 左右都不为空:找出替换节点:右子树最小节点**、**左子树最大节点。替换节点可以作为交换和删除进行交换,交换后删除交换节点、交换节点要么没有孩子,要么只有一个孩子可以直接删除

      但是左右都为空可以纳入到左为空或右为空的情况

      【数据结构】二叉搜索树BSTree

      【数据结构】二叉搜索树BSTree

      【数据结构】二叉搜索树BSTree

      注意:

      【数据结构】二叉搜索树BSTree

      代码实现:

      bool Erase(const K& key)
      	{
      		Node* parent = nullptr;
      		Node* cur = _root;
      		while (cur)
      		{
      			if (cur->_key < key)
      			{
      				parent = cur;
      				cur = cur->_right;
      			}
      			else if (cur->_key > key)
      			{
      				parent = cur;
      				cur = cur->_left;
      			}
      			else
      			{
      				//左为空
      				if (cur->_left == nullptr)
      				{
      					//删除根结点
      					//if(parent==nullptr)
      					if (cur == _root)
      					{
      						_root = cur->_right;
      					}
      					else
      					{
      						if (parent->_left == cur)
      						{
      							parent->_left = cur->_right;
      						}
      						else
      						{
      							parent->_right = cur->_right;
      						}
      					}
      					delete cur;
      				}
      				//右为空
      				else if (cur->_right == nullptr)
      				{
      					if (cur == _root)
      					{
      						_root = cur->_left;
      					}
      					else
      					{
      						if (parent->_left == cur)
      						{
      							parent->_left = cur->_left;
      						}
      						else
      						{
      							parent->_right = cur->_left;
      						}
      					}
      					delete cur;
      				}
      				//左右都不为空,找替换节点
      				else
      				{
      					//不能初始化为nullptr
      					Node* parent = cur;
      					//右子树最小节点
      					Node* minRight = cur->_right;
      					while (minRight->_left)
      					{
      						parent = minRight;
      						minRight = minRight->_left;
      					}
      					cur->_key = minRight->_key;
      					//判断minRight是父亲的左还是右
      					if (minRight == parent->_left)
      					{
      						parent->_left = minRight->_right;
      					}
      					else
      					{
      						parent->_right = minRight->_right;
      					}
      					delete minRight;
      				}
      				return true;
      			}
      		}
      		return false;
      	}
      

      三、递归写法

      1.递归查找

      这个比较简单:苏醒把,递归时刻

      bool _FindR(Node* root, const K& key)
      	{
      		if (root == nullptr) return false;
      		else if (root->_key < key) return _FindR(root->_right, key);
      		else if (root->_key > key) return _FindR(root->_left, key);
      		else return true;
      	}
      

      2.递归插入

      最大的问题是插入之后跟父亲进行链接,如果直接给root是不可以的,因为root是栈帧里面的参数,只是局部变量:加上引用

      bool _InsertR(Node*& root, const K& key)
      	{
      		if (root == nullptr)
      		{
      			root = new Node(key);
      			return true;
      		}
      		else if (root->_key < key) 
      			return _InsertR(root->_right, key);
      		else if (root->_key > key) 
      			return _InsertR(root->_left, key);
      		else 
      			return false;
      	}
      

      【数据结构】二叉搜索树BSTree

      3.递归删除

      递归删除怎么找到父节点?root = root->_left/ root = root->_right;

      【数据结构】二叉搜索树BSTree

      bool _EraseR(Node*& root, const K& key)
      	{
      		if (root == nullptr)
      		{
      			return false;
      		}
      		if (root->_key < key)
      		{
      			return _EraseR(root->_right, key);
      		}
      		else if (root->_key > key)
      		{
      			return _EraseR(root->_left, key);
      		}
      		else
      		{
      			Node* del = root;
      			if (root->_right == nullptr)
      			{
      				root = root->_left;
      			}
      			else if (root->_left == nullptr)
      			{
      				root = root->_right;
      			}
      			else
      			{
      				Node* minRight = root->_right;
      				while (minRight->_left)
      				{
      					minRight = minRight->_left;
      				}
      				swap(root->_key, minRight->_key);
      				return _EraseR(root->_right, key);
      			}
      			delete del;
      			return true;
      		}
      	}
      

      四、应用

      最优情况下,二叉搜索树为完全二叉树,其平均比较次数为:log2N
      最差情况下,二叉搜索树退化为单支树,其平均比较次数为: N/2

      【数据结构】二叉搜索树BSTree

      1.K模型:K模型即只有key作为关键码,结构中只需要存储Key即可,关键码即为需要搜索到的值,判断关键字是否存在。
      比如:给一个单词word,判断该单词是否拼写正确,具体方式如下:
      以单词集合中的每个单词作为key,构建一棵二叉搜索树,在二叉搜索树中检索该单词是否存在,存在则拼写正确,不存在则拼写错误。

      2.KV模型:每一个关键码key,都有与之对应的值Value,即**<Key, Value>**的键值对。

      比如英汉词典就是英文与中文的对应关系,通过英文可以快速找到与其对应的中文,英文单词与其对应的中文<word, chinese>就构成一种键值对;再比如统计单词次数,统计成功后,给定单词就可快速找到其出现的次数,单词与其出现次数就是**<word, count>**就构成一种键值对。

      namespace KV
      {
      	template <class K,class V>
      	struct BSTreeNode
      	{
      		BSTreeNode<K,V>* _left;
      		BSTreeNode<K,V>* _right;
      		K _key;
      		V _value;
      
      		BSTreeNode(const K& key,const V&value)
      			:_key(key),
      			_value(value),
      			_left(nullptr),
      			_right(nullptr)
      		{}
      	};
      
      	template <class K,class V>
      	class BSTree
      	{
              typedef BSTreeNode<K, V> Node;
      	public:
      		bool Insert(const K& key, const V& value)
      
      		Node* find(const K& key)
      
      		void InOrder()
      	private:
      		Node* _root = nullptr;
      	};
      }
      void TestBSTree()
      {
      	//key/Value的搜索模型;通过key查找或修改Value
      	KV::BSTree<string, string> dict;
      	dict.Insert("sort", "排序");
      	dict.Insert("string", "字符串");
      	dict.Insert("left", "左");
      	dict.Insert("right", "右");
      	string str;
      	while (cin >> str)
      	{
      		KV::BSTreeNode<string, string>* ret = dict.find(str);
      		if (ret)
      		{
      			cout << ret->_value << endl;
      		}
      		else
      		{
      			cout << "找不到" << endl;
      		}
      	}
      
      }
      

      源代码:

      BSTree.h

      #include <iostream>
      using namespace std;
      
      namespace K
      {
      	template <class K>
      	struct BSTreeNode
      	{
      		BSTreeNode<K>* _left;
      		BSTreeNode<K>* _right;
      		K _key;
      
      		BSTreeNode(const K& key)
      			:_key(key),
      			_left(nullptr),
      			_right(nullptr)
      		{}
      	};
      	template <class K>
      	class BSTree
      	{
      		typedef BSTreeNode<K> Node;
      	public:
      		BSTree()
      			:_root(nullptr)
      		{}
      
      		BSTree(const BSTree<K>& t)
      		{
      			_root = Copy(t._root);
      		}
      
      		BSTree<K>& operator = (BSTree<K> t)
      		{
      			swap(_root, t._root);
      			return *this;
      		}
      		~BSTree()
      		{
      			Destroy(_root);
      			_root = nullptr;
      		}
      
      
      		bool Insert(const K& key)
      		{
      			if (_root == nullptr)
      			{
      				_root = new Node(key);
      				return true;
      			}
      			Node* parent = nullptr;
      			Node* cur = _root;
      			while (cur)
      			{
      				if (cur->_key < key)
      				{
      					parent = cur;
      					cur = cur->_right;
      				}
      				else if (cur->_key > key)
      				{
      					parent = cur;
      					cur = cur->_left;
      				}
      				else
      				{
      					return false;
      				}
      			}
      			cur = new Node(key);
      			if (parent->_key < key)
      			{
      				parent->_right = cur;
      			}
      			else
      			{
      				parent->_left = cur;
      			}
      			return true;
      		}
      
      		bool find(const K& key)
      		{
      			Node* cur = _root;
      			while (cur)
      			{
      				if (cur->_key < key)
      				{
      					cur = cur->_right;
      				}
      				else if (cur->_key > key)
      				{
      					cur = cur->_left;
      				}
      				else
      				{
      					return true;
      				}
      			}
      			return false;
      		}
      
      		bool Erase(const K& key)
      		{
      			Node* parent = nullptr;
      			Node* cur = _root;
      			while (cur)
      			{
      				if (cur->_key < key)
      				{
      					parent = cur;
      					cur = cur->_right;
      				}
      				else if (cur->_key > key)
      				{
      					parent = cur;
      					cur = cur->_left;
      				}
      				else
      				{
      					//左为空
      					if (cur->_left == nullptr)
      					{
      						//删除根结点
      						//if(parent==nullptr)
      						if (cur == _root)
      						{
      							_root = cur->_right;
      						}
      						else
      						{
      							if (parent->_left == cur)
      							{
      								parent->_left = cur->_right;
      							}
      							else
      							{
      								parent->_right = cur->_right;
      							}
      						}
      						delete cur;
      					}
      					//右为空
      					else if (cur->_right == nullptr)
      					{
      						if (cur == _root)
      						{
      							_root = cur->_left;
      						}
      						else
      						{
      							if (parent->_left == cur)
      							{
      								parent->_left = cur->_left;
      							}
      							else
      							{
      								parent->_right = cur->_left;
      							}
      						}
      						delete cur;
      					}
      					//左右都不为空,找替换节点
      					else
      					{
      						//不能初始化为nullptr
      						Node* parent = cur;
      						//右子树最小节点
      						Node* minRight = cur->_right;
      						while (minRight->_left)
      						{
      							parent = minRight;
      							minRight = minRight->_left;
      						}
      						cur->_key = minRight->_key;
      						//判断minRight是父亲的左还是右
      						if (minRight == parent->_left)
      						{
      							parent->_left = minRight->_right;
      						}
      						else
      						{
      							parent->_right = minRight->_right;
      						}
      						delete minRight;
      					}
      					return true;
      				}
      			}
      			return false;
      		}
      
      
      		void InOrder()
      		{
      			_InOrder(_root);
      			cout << endl;
      		}
      
              //递归
      		bool InsertR(const K& key)
      		{
      			return _InsertR(_root, key);
      		}
      
      		bool FindR(const K& key)
      		{
      			return _FindR(_root, key);
      		}
      
      		bool EraseR(const K& key)
      		{
      			return _EraseR(_root, key);
      		}
      
      	private:
      		void Destroy(Node* root)
      		{
      			if (root == nullptr)
      			{
      				return;
      			}
      			Destroy(root->_left);
      			Destroy(root->_right);
      			delete root;
      		}
      
      		Node* Copy(Node* root)
      		{
      			if (root == nullptr)
      				return nullptr;
      			Node* newRoot = new Node(root->_key);
      			newRoot->_left = Copy(root->_left);
      			newRoot->_right = Copy(root->_right);
      			return newRoot;
      		}
      
      		bool _EraseR(Node*& root, const K& key)
      		{
      			if (root == nullptr)
      			{
      				return false;
      			}
      			if (root->_key < key)
      			{
      				return _EraseR(root->_right, key);
      			}
      			else if (root->_key > key)
      			{
      				return _EraseR(root->_left, key);
      			}
      			else
      			{
      				Node* del = root;
      				if (root->_right == nullptr)
      				{
      					root = root->_left;
      				}
      				else if (root->_left == nullptr)
      				{
      					root = root->_right;
      				}
      				else
      				{
      					Node* minRight = root->_right;
      					while (minRight->_left)
      					{
      						minRight = minRight->_left;
      					}
      					swap(root->_key, minRight->_key);
      					return _EraseR(root->_right, key);
      				}
      				delete del;
      				return true;
      			}
      		}
      
      		bool _InsertR(Node*& root, const K& key)
      		{
      			if (root == nullptr)
      			{
      				root = new Node(key);
      				return true;
      			}
      			else if (root->_key < key)
      				return _InsertR(root->_right, key);
      			else if (root->_key > key)
      				return _InsertR(root->_left, key);
      			else
      				return false;
      		}
      
      		bool _FindR(Node* root, const K& key)
      		{
      			if (root == nullptr) return false;
      			else if (root->_key < key) return _FindR(root->_right, key);
      			else if (root->_key > key) return _FindR(root->_left, key);
      			else return true;
      		}
      
      		void _InOrder(Node* root)
      		{
      			if (root == nullptr)
      			{
      				return;
      			}
      			_InOrder(root->_left);
      			cout << root->_key << " ";
      			_InOrder(root->_right);
      		}
      		Node* _root = nullptr;
      	};
      }
      
      namespace KV
      {
      	template <class K,class V>
      	struct BSTreeNode
      	{
      		BSTreeNode<K,V>* _left;
      		BSTreeNode<K,V>* _right;
      		K _key;
      		V _value;
      
      		BSTreeNode(const K& key,const V&value)
      			:_key(key),
      			_value(value),
      			_left(nullptr),
      			_right(nullptr)
      		{}
      	};
      
      	template <class K,class V>
      	class BSTree
      	{
      		typedef BSTreeNode<K, V> Node;
      	public:
      		bool Insert(const K& key, const V& value)
      		{
      			if (_root == nullptr)
      			{
      				_root = new Node(key, value);
      				return true;
      			}
      			Node* parent = nullptr;
      			Node* cur = _root;
      			while (cur)
      			{
      				if (cur->_key < key)
      				{
      					parent = cur;
      					cur = cur->_right;
      				}
      				else if (cur->_key > key)
      				{
      					parent = cur;
      					cur = cur->_left;
      				}
      				else
      				{
      					return false;
      				}
      			}
      			cur = new Node(key, value);
      			if (parent->_key < key)
      			{
      				parent->_right = cur;
      			}
      			else
      			{
      				parent->_left = cur;
      			}
      			return true;
      		}
      
      		Node* find(const K& key)
      		{
      			Node* cur = _root;
      			while (cur)
      			{
      				if (cur->_key < key)
      				{
      					cur = cur->_right;
      				}
      				else if (cur->_key > key)
      				{
      					cur = cur->_left;
      				}
      				else
      				{
      					return cur;
      				}
      			}
      			return nullptr;
      		}
      		void InOrder()
      		{
      			_InOrder(_root);
      		}
      	private:
      		void _InOrder(Node* root)
      		{
      			if (root == nullptr) return;
      			_InOrder(root->_left);
      			cout << root->_key << ":"<<root->_value<<endl;
      			_InOrder(root->_right);
      		}
      		Node* _root = nullptr;
      	};
      }
      void TestBSTree1()
      {
      	int a[] = { 8, 3, 1, 10, 6, 4, 7, 14, 13 };
      	K::BSTree<int> t;
      	for (auto e : a)
      	{
      		t.Insert(e);
      	}
      	t.InOrder();
      	K::BSTree<int> copyt(t);
      	copyt.InOrder();
      	t.InsertR(9);
      	t.InOrder();
      	t.EraseR(9);
      	t.InOrder();
      
      	t.EraseR(3);
      	t.InOrder();
      
      	for (auto e : a)
      	{
      		t.EraseR(e);
      	    t.InOrder();
      	}
      }
      void TestBSTree2()
      {
      	KV::BSTree<string, string> dict;
      	dict.Insert("sort", "排序");
      	dict.Insert("string", "字符串");
      	dict.Insert("left", "左");
      	dict.Insert("right", "右");
      	string str;
      	while (cin >> str)
      	{
      		KV::BSTreeNode<string, string>* ret = dict.find(str);
      		if (ret)
      		{
      			cout << ret->_value << endl;
      		}
      		else
      		{
      			cout << "找不到" << endl;
      		}
      	}
      
      }
      void TestBSTree3()
      {
      	string arr[] = { "苹果","西瓜","苹果" };
      	KV::BSTree<string, int> countTree;
      	for (auto e : arr)
      	{
      		auto* ret = countTree.find(e);
      		if (ret == nullptr)
      		{
      			countTree.Insert(e, 1);
      		}
      		else
      		{
      			ret->_value++;
      		}
      	}
      	countTree.InOrder();
      }
      
      #include "BSTree.h"
      int main()
      {
          //TestBSTree1();
      	TestBSTree2();
          //TestBSTree3();
      	return 0;
      }
      

      五、题目练习

      根据二叉树创建字符串

      【数据结构】二叉搜索树BSTree

      前序遍历,左为空,右不为空的括号不可以省略,右为空的括号可以省略

      class Solution {
      public:
          string tree2str(TreeNode* root) {
              if(root == nullptr) return string();
              string ret;
              ret += to_string(root->val);
              if(root->left)
              {
                  ret+='(';
                  ret+= tree2str(root->left);
                  ret+=')';
              }
              else if(root->right)
              {
                  ret+="()";
              }
      
              if(root->right)
              {
                  ret+='(';
                  ret+=tree2str(root->right);
                  ret+=')';
              }
              return ret;
      
          }
      };
      

      二叉树的层序遍历

      【数据结构】二叉搜索树BSTree

      层序遍历,可以通过一个队列来实现,同时定义每次队列的大小

      class Solution {
      public:
          vector<vector<int>> levelOrder(TreeNode* root) {
              queue<TreeNode*> q;
              vector<vector<int>> vv;
              size_t levelSize = 0;
              if(root)
              {
                  q.push(root);
                  levelSize=1;
              }
              while(!q.empty())
              {
                  vector<int> v;
                  while(levelSize--)
                  {
                      TreeNode* front = q.front();
                      q.pop();
                      v.push_back(front->val);
                      if(front->left)
                      {
                          q.push(front->left);
                      }
                      if(front->right)
                      {
                          q.push(front->right);
                      }
                  }
                  vv.push_back(v);
                  levelSize = q.size();
              }
              return vv;
          }
      };
      

      二叉树的最近公共祖先

      【数据结构】二叉搜索树BSTree

      【数据结构】二叉搜索树BSTree

      class Solution {
          bool isInTree(TreeNode*root,TreeNode*x)
          {
              if(root == nullptr) return false;
              if(root == x) return true;
              else 
                  return isInTree(root->left,x)
                      || isInTree(root->right,x);
          }
      public:
          TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
              if(root==nullptr)
                  return nullptr;
              if(root == p||root==q) return root;
              bool pLeft = isInTree(root->left,p);
              bool pRight = !pLeft;
              bool qLeft = isInTree(root->left,q);
              bool qRight = !qLeft;
              //一个在左一个在右
              if((pLeft&&qRight)||(pRight&&qLeft))
                  return root;
              //同左
              if(pLeft&&qLeft)
                  return lowestCommonAncestor(root->left,p,q);
              //同右
              else
                  return lowestCommonAncestor(root->right,p,q);
          }
      };
      

      把根到对应节点的路径存储起来,在找出相交的结点即是最近的公共结点:

      【数据结构】二叉搜索树BSTree

      class Solution {
          bool GetPath(TreeNode*root,TreeNode*x,stack<TreeNode*>& stack)
          {
              if(root == nullptr) return false;
              stack.push(root);
              if(root == x)
              {
                  return true;
              }
              if(GetPath(root->left,x,stack))
                  return true;
              if(GetPath(root->right,x,stack))
                  return true;
              stack.pop();
              return false;
          }
      public:
          TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
              if(root==nullptr)
                  return nullptr;
              stack<TreeNode*> pPath;
              stack<TreeNode*> qPath;
              GetPath(root,p,pPath);
              GetPath(root,q,qPath);
              //长的先pop
              while(pPath.size()!=qPath.size())
              {
                  if(pPath.size()>qPath.size())
                  {
                      pPath.pop();
                  }
                  else
                      qPath.pop();
              }
              //同时pop,找出交点
              while(()!=())
              {
                  pPath.pop();
                  qPath.pop();
              }
              return ();
          }
      };
      

      二叉搜索树与双向链表

      【数据结构】二叉搜索树BSTree

      思路一:中序遍历,将节点放到一个vector中,在链接节点,但是空间复杂度不符合题目要求:

      class Solution {
      	void InOrder(TreeNode*root,vector<TreeNode*>& v)
      	{
      		if(root==nullptr) return;
      		InOrder(root->left,v);
      		v.push_back(root);
      		InOrder(root->right,v);
      	}
      public:
          TreeNode* Convert(TreeNode* pRootOfTree) {
      		if(pRootOfTree==nullptr) return nullptr;
      		vector<TreeNode*> v;
      		InOrder(pRootOfTree,v);
      		if(v.size()<=1) return v[0];
      		v[0]->left =nullptr;
      		v[0]->right = v[1];
      		for(int i =1;i<v.size()-1;i++)
      		{
      			v[i]->left = v[i-1];
      			v[i]->right = v[i+1];
      		}
      		v[v.size()-1]->left = v[v.size()-2];
      		v[v.size()-1]->right = nullptr;
      		return v[0];
      	}
      };
      

      思路二:递归直接进行转换

      【数据结构】二叉搜索树BSTree

      class Solution {
      	void InOrder(TreeNode*cur,TreeNode*&prev)
      	{
      		if(cur==nullptr)
      		{
      			return;
      		}
      		InOrder(cur->left,prev);
      		cur->left = prev;
      		if(prev)
      		{
      			prev->right = cur;
      		}
      		prev = cur;
      		InOrder(cur->right,prev);
      	}
      
      public:
          TreeNode* Convert(TreeNode* pRootOfTree) {
      		TreeNode*prev = nullptr;
      		InOrder(pRootOfTree,prev);
      		//找头
      		TreeNode*head = pRootOfTree;
      		while(head&&head->left)
      		{
      			head = head->left;
      		}
      		return head;
      	}
      };
      

      从前序与中序遍历序列构造二叉树

      【数据结构】二叉搜索树BSTree

      根据前序结果去创建树,前序是根左右,前序第一个元素就是根,在通过中序去进行分割左右子树。子树区间确认是否继续递归创建子树,区间不存在则是空树。所以根据前序先构造根,在通过中序构造左子树、在构造右子树即可。

      class Solution {
          TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,int&prei,int inbegin,int inend)
          {
              if(inbegin>inend)
              {
                  return nullptr;
              }
              TreeNode*root = new TreeNode(preorder[prei]);
              int rooti = inbegin;
              while(inbegin<=inend)
              {
                  if(preorder[prei] == inorder[rooti])
                  {
                      break;
                  }
                  else rooti++;
              }
              prei++;
              //[inbegin,rooti-1]rooti[rooti+1,inend]
              root->left= _buildTree(preorder,inorder,prei,inbegin,rooti-1);
              root->right = _buildTree(preorder,inorder,prei,rooti+1,inend);
              return root;
          }
      public:
          TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
              int prei = 0;
             return _buildTree(preorder,inorder,prei,0,inorder.size()-1);
          }
      };
      

      传引用问题:因为prei是遍历前序数组开始的下标,整个递归遍历中都要使用,所以我们需要传引用。如果不是传引用而是传值的话,左子树构建好返回,如果此时prei不是传引用,只是形参,无法将上一次递归的结果保留下来,那么也就无构建右子树了。

      从中序与后序遍历序列构造二叉树

      【数据结构】二叉搜索树BSTree

      根据后序遍历的最后一个元素可以确定根结点,有了根结点做为切割点然后再去根据中序遍历划分左右区间,在继续下去,构造成二叉树,区间不存在就是空树了。同时,后序遍历是左右根,所以最后一个是根节点。所以当我们构造根结点后,由于前面是右子树,所以先构造右子树,在构造左子数。

      class Solution {
          TreeNode* _buildTree(vector<int>& inorder, vector<int>& postorder,int &posi,int inbegin,int inend)
          {
              if(inbegin>inend)
              {
                  return nullptr;
              }
              TreeNode* root = new TreeNode(postorder[posi]);
              int rooti = inbegin;
              while(inbegin<=inend)
              {
                  if(postorder[posi] == inorder[rooti])
                  {
                      break;
                  }
                  else rooti++;
              }
              posi--;
              //[inbegin,rooti-1]rooti[rooti+1,inend];
              root->right = _buildTree(inorder,postorder,posi,rooti+1,inend);
              root->left = _buildTree(inorder,postorder,posi,inbegin,rooti-1);
              return root;
          }
      public:
          TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
              int posi = postorder.size()-1;
              return _buildTree(inorder,postorder,posi,0,inorder.size()-1);
          }
      };
      

      【数据结构】二叉搜索树BSTree

      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.csdn.net/weixin_60478154/article/details/128933791,作者:平凡的人1,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇: mysql-innodb-自定义函数-函数参数赋值-记录

      下一篇:记录一次事故处理50%kudu表无法进行正常访问

      相关文章

      2025-05-19 09:04:53

      查看RISC-V版本的gcc中默认定义的宏

      查看RISC-V版本的gcc中默认定义的宏

      2025-05-19 09:04:53
      c++ , linux
      2025-04-14 09:26:51

      【算法入门08】青蛙跳台阶

      【算法入门08】青蛙跳台阶

      2025-04-14 09:26:51
      c++ , 动态规划 , 算法
      2025-04-14 09:26:51

      STL详解(九)—— priority_queue的使用与模拟实现

      优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中的元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。

      2025-04-14 09:26:51
      c++ , stl , 数据结构
      2025-04-14 09:26:51

      STL详解(八)—— stack和queue的模拟实现

      stack和queue有一点需要注意的是,虽然stack和queue中也可以存放元素,但在STL中并没有将其划分在容器的行列,而是将其称为容器适配器,这是因为stack和queue只是对其他容器的接口进行了包装,STL中stack和queue默认使用deque容器。

      2025-04-14 09:26:51
      c++ , queue , stack , stl
      2025-04-14 09:24:23

      【算法入门14】二叉树的镜像

      【算法入门14】二叉树的镜像

      2025-04-14 09:24:23
      c++ , 算法
      2025-04-14 09:24:23

      【算法入门09】矩形覆盖

      【算法入门09】矩形覆盖

      2025-04-14 09:24:23
      c++ , 动态规划 , 算法
      2025-04-01 10:29:12

      golang与 C++数据结构类型对应关系是怎样的?

      uintptr和unsafe.Pointer相当于c++的void*,也就是任意指针。

      2025-04-01 10:29:12
      c++ , golang , 函数指针 , 数据结构
      2025-03-31 08:49:25

      MFC编程 -- 判断是否按下ctrl和shift键

      MFC编程 -- 判断是否按下ctrl和shift键

      2025-03-31 08:49:25
      c++ , mfc , 开发语言
      2025-03-31 08:48:59

      MFC编程 -- 读取文件内容

      MFC编程 -- 读取文件内容

      2025-03-31 08:48:59
      c++ , mfc
      2025-03-31 08:48:59

      MFC编程 -- 浮点数与字符串之间转换

      MFC编程 -- 浮点数与字符串之间转换

      2025-03-31 08:48:59
      c++ , mfc , 字符串 , 浮点数
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5264186

      查看更多

      最新文章

      STL详解(九)—— priority_queue的使用与模拟实现

      2025-04-14 09:26:51

      空间换时间:数据结构中时间复杂度于空间复杂度的“转换”

      2024-10-24 08:01:02

      利用循环与递归实现二分查找

      2024-10-24 08:01:02

      字符串中的第一个唯一字符(基数排序的思想应用)

      2024-10-17 08:21:52

      150. 逆波兰表达式求值

      2024-09-24 06:30:42

      按照二叉树的每行个数打印数组

      2024-06-24 08:13:04

      查看更多

      热门文章

      1223. 数字字符统计

      2023-03-21 10:30:43

      【算法】双指针、位运算、离散化、合并区间

      2023-07-26 08:09:55

      leetcode394. 字符串解码

      2024-04-03 09:23:50

      字典序最小问题(贪心)

      2024-03-18 08:33:44

      leetcode606. 根据二叉树创建字符串

      2024-04-03 09:23:58

      每日一题-102. 二叉树的层序遍历

      2024-05-09 09:22:19

      查看更多

      热门标签

      数据库 mysql 字符串 数据结构 MySQL 算法 redis oracle java sql python 数据 索引 SQL 查询
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      数据结构资源下载导航【数据结构】

      字符串中的第一个唯一字符(基数排序的思想应用)

      【算法】双指针、位运算、离散化、合并区间

      150. 逆波兰表达式求值

      leetcode2068. 检查两个字符串是否几乎相等

      空间换时间:数据结构中时间复杂度于空间复杂度的“转换”

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号