爆款云主机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云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      二叉树简介及C++实现

      首页 知识中心 软件开发 文章详情页

      二叉树简介及C++实现

      2023-04-18 14:13:07 阅读次数:527

      C++,二叉树

      二叉树是每个结点最多有两个子树的树结构,即结点的度最大为2。通常子树被称作”左子树”和”右子树”。二叉树是一个连通的无环图。

      二叉树是递归定义的,其结点有左右子树之分,逻辑上二叉树有五种基本形态:(1)、空二叉树;(2)、只有一个根结点的二叉树;(3)、只有左子树;(4)、只有右子树;(5)、完全二叉树。

      二叉树类型:

      (1)、满二叉树:深度(层数)为k,且有2^k-1个结点的二叉树。这种树的特点是每一层上的结点数都是最大结点数。即除了叶结点外每一个结点都有左右子树且叶节点都处在最低层。

      (2)、完全二叉树:除最后一层外,其余层都是满的,并且最后一层或者是满的,或者是在右边缺少连续若干节点,即叶子结点都是从左到右依次排布。具有n个节点的完全二叉树的深度为floor(log(2n))+1。深度为k的完全二叉树,至少有2^(k-1)个结点,至多有(2^k)-1个结点。

      (3)、平衡二叉树:又被称为AVL树,它是一颗二叉排序树,且具有以下性质:它是一颗空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一颗平衡二叉树。

      (4)、斜树:所有的结点都只有左子树(左斜树),或者只有右子树(右斜树)。

      (5)、二叉搜素树(或二叉排序树):特殊的二叉树,每个结点都不比它左子树的任意元素小,而且不比它的右子树的任意元素大。二叉搜索树的左右子树也都是二叉搜索树。按中序遍历,则会得到按升序排列的有序数据集。

      二叉树不是树的一种特殊情形。

      遍历二叉树:按一定的规则和顺序走遍二叉树的所有结点,使每一个结点都被访问一次,而且只被访问一次。对一颗二叉树的遍历有四种情况:先序遍历、中序遍历、后序遍历、按层遍历。

      (1)、先序遍历:先访问根结点,再先序遍历左子树,最后再先序遍历右子树,即先访问根结点-------左子树------右子树。

      (2)、中序遍历:先中序遍历左子树,然后再访问根结点,最后再中序遍历右子树,即先访问左子树------根结点------右子树。

      (3)、后序遍历:先后序遍历左子树,然后再后序遍历右子树,最后再访问根结点,即先访问左子树------右子树------根结点。

      (4)、按层遍历:从上到下,从左到右依次访问结点。

      下面代码是二叉搜索树的实现,主要包括树的创建、插入、删除、查找、遍历、保存、载入。

      binary_search_tree.hpp:

      #ifndef FBC_CPPBASE_TEST_BINARY_SEARCH_TREE_HPP_
      #define FBC_CPPBASE_TEST_BINARY_SEARCH_TREE_HPP_
      
      #include <vector>
      #include <fstream>
      #include <string>
      
      namespace binary_search_tree_ {
      
      typedef struct info {
      	int id; // suppose id is unique
      	std::string name;
      	int age;
      	std::string addr;
      } info;
      
      typedef struct node {
      	info data;
      	node* left = nullptr;
      	node* right = nullptr;
      } node;
      
      class BinarySearchTree {
      public:
      	BinarySearchTree() = default;
      	~BinarySearchTree() { DeleteTree(tree); }
      
      	typedef std::tuple<int, int, std::string, int, std::string> row; // flag(-1: no node, 0: have a node), id, name, age, addr
      
      	int Init(const std::vector<info>& infos); // create binary search tree
      	bool Search(int id, info& data) const;
      	int Insert(const info& data);
      	int Delete(int id); // delete a node
      	int Traversal(int type) const; // 0: pre-order, 1: in-order, 2: post-order, 3: level
      	int GetMaxDepth() const; // get tree max depth
      	int GetMinDepth() const; // get tree min depth
      	int GetNodesCount() const; // get tree node count
      	bool IsBinarySearchTree() const; // whether or not is a binary search tree
      	//bool IsBinaryBalanceTree() const; // whether ot not is a binary balance tree
      	int GetMinValue(info& data) const;
      	int GetMaxValue(info& data) const;
      	int SaveTree(const char* name) const; // tree write in txt file
      	int LoadTree(const char* name);
      
      protected:
      	void PreorderTraversal(const node* ptr) const;
      	void InorderTraversal(const node* ptr) const;
      	void PostorderTraversal(const node* ptr) const;
      	void LevelTraversal(const node* ptr) const;
      	void LevelTraversal(const node* ptr, int level) const;
      	void DeleteTree(node* ptr);
      	void Insert(node* ptr, const info& data);
      	const node* Search(const node* ptr, int id) const;
      	void IsBinarySearchTree(const node* ptr, bool is_bst) const;
      	int GetNodesCount(const node* ptr) const;
      	int GetMaxDepth(const node* ptr) const;
      	int GetMinDepth(const node* ptr) const;
      	//bool IsBinaryBalanceTree(const node* ptr) const;
      	node* Delete(node* ptr, int id); // return new root
      	node* GetMinValue(node* ptr);
      	void NodeToRow(const node* ptr, std::vector<row>& rows, int pos) const;
      	void RowToNode(node* ptr, const std::vector<row>& rows, int n, int pos);
      
      private:
      	node* tree = nullptr;
      	bool flag;
      };
      
      int test_binary_search_tree();
      
      } // namespace binary_search_tree_
      
      #endif // FBC_CPPBASE_TEST_BINARY_SEARCH_TREE_HPP_
      

      binary_search_tree.cpp:

      #include "binary_search_tree.hpp"
      #include <set>
      #include <iostream>
      #include <limits>
      #include <tuple>
      #include <string>
      #include <sstream>
      #include <string.h>
      #include <algorithm>
      
      namespace binary_search_tree_ {
      
      int BinarySearchTree::Init(const std::vector<info>& infos)
      {
      	std::vector<int> ids;
      	for (const auto& info : infos) {
      		ids.emplace_back(info.id);
      	}
      
      	std::set<int> id_set(ids.cbegin(), ids.cend());
      	if (id_set.size() != ids.size()) {
      		fprintf(stderr, "id must be unique\n");
      		return -1;
      	}
      
      	for (const auto& info : infos) {
      		Insert(info);
      	}
      
      	return 0;
      }
      
      bool BinarySearchTree::Search(int id, info& data) const
      {
      	const node* root = tree;
      	const node* tmp = Search(root, id);
      	if (tmp) {
      		data = tmp->data;
      		return true;
      	} else {
      		return false;
      	}
      }
      
      const node* BinarySearchTree::Search(const node* ptr, int id) const
      {
      	if (ptr) {
      		if (ptr->data.id == id) {
      			return ptr;
      		} else if (ptr->data.id > id) {
      			return Search(ptr->left, id);
      		} else {
      			return Search(ptr->right, id);
      		}
      	} else {
      		return nullptr;
      	}
      }
      
      int BinarySearchTree::Insert(const info& data)
      {
      	flag = true;
      
      	if (tree) {
      		Insert(tree, data);
      	} else {
      		tree = new node;
      		tree->data = data;
      		tree->left = nullptr;
      		tree->right = nullptr;
      	}
      
      	return (int)flag;
      }
      
      void BinarySearchTree::Insert(node* ptr, const info& data)
      {
      	if (ptr->data.id == data.id) {
      		flag = false;
      		return;
      	}
      
      	if (ptr->data.id < data.id) {
      		if (ptr->right) {
      			Insert(ptr->right, data);
      		} else {
      			ptr->right = new node;
      			ptr->right->data = data;
      			ptr->right->left = nullptr;
      			ptr->right->right = nullptr;
      		}
      	} else {
      		if (ptr->left) {
      			Insert(ptr->left, data);
      		} else {
      			ptr->left = new node;
      			ptr->left->data = data;
      			ptr->left->left = nullptr;
      			ptr->left->right = nullptr;
      		}
      	}
      }
      
      bool BinarySearchTree::IsBinarySearchTree() const
      {
      	bool is_bst = true;
      	const node* root = tree;
      	IsBinarySearchTree(root, is_bst);
      
      	return is_bst;
      }
      
      void BinarySearchTree::IsBinarySearchTree(const node* ptr, bool is_bst) const
      {
      	static int last_data = std::numeric_limits<int>::min();
      	if (!ptr) return;
      
      	IsBinarySearchTree(ptr->left, is_bst);
      
      	if (last_data < ptr->data.id) last_data = ptr->data.id;
      	else {
      		is_bst = false;
      		return;
      	}
      
      	IsBinarySearchTree(ptr->right, is_bst);
      }
      
      int BinarySearchTree::Traversal(int type) const
      {
      	if (!tree) {
      		fprintf(stderr, "Error: it is an empty tree\n");
      		return -1;
      	}
      
      	const node* root = tree;
      	if (type == 0)
      		PreorderTraversal(root);
      	else if (type == 1)
      		InorderTraversal(root);
      	else if (type == 2)
      		PostorderTraversal(root);
      	else if (type == 3)
      		LevelTraversal(root);
      	else {
      		fprintf(stderr, "Error: don't suppot traversal type, type only support: 0: pre-order, 1: in-order, 2: post-order\n");
      		return -1;
      	}
      
      	return 0;
      }
      
      void BinarySearchTree::PreorderTraversal(const node* ptr) const
      {
      	if (ptr) {
      		fprintf(stdout, "Info: id: %d, name: %s, age: %d, addr: %s\n",
      			ptr->data.id, ptr->data.name.c_str(), ptr->data.age, ptr->data.addr.c_str());
      		PreorderTraversal(ptr->left);
      		PreorderTraversal(ptr->right);
      	} 
      }
      
      void BinarySearchTree::InorderTraversal(const node* ptr) const
      {
      	if (ptr) {
      		InorderTraversal(ptr->left);
      		fprintf(stdout, "Info: id: %d, name: %s, age: %d, addr: %s\n",
      			ptr->data.id, ptr->data.name.c_str(), ptr->data.age, ptr->data.addr.c_str());
      		InorderTraversal(ptr->right);
      	} 
      }
      
      void BinarySearchTree::PostorderTraversal(const node* ptr) const
      {
      	if (ptr) {
      		PostorderTraversal(ptr->left);
      		PostorderTraversal(ptr->right);
      		fprintf(stdout, "Info: id: %d, name: %s, age: %d, addr: %s\n",
      			ptr->data.id, ptr->data.name.c_str(), ptr->data.age, ptr->data.addr.c_str());
      	} 
      }
      
      void BinarySearchTree::LevelTraversal(const node* ptr) const
      {
      	int h = GetMaxDepth();
      
      	for (int i = 1; i <= h; ++i)
      		LevelTraversal(ptr, i);	
      }
      
      void BinarySearchTree::LevelTraversal(const node* ptr, int level) const
      {
      	if (!ptr) return;
      
      	if (level == 1)
      		fprintf(stdout, "Info: id: %d, name: %s, age: %d, addr: %s\n",
      			ptr->data.id, ptr->data.name.c_str(), ptr->data.age, ptr->data.addr.c_str());
      	else if (level > 1) {
      		LevelTraversal(ptr->left, level-1);
      		LevelTraversal(ptr->right, level-1);
      	}
      }
      
      void BinarySearchTree::DeleteTree(node* ptr)
      {
      	if (ptr) {	
      		DeleteTree(ptr->left);
      		DeleteTree(ptr->right);
      		delete ptr;
      	}
      }
      
      int BinarySearchTree::GetNodesCount() const
      {	
      	const node* root = tree;
      	return GetNodesCount(root);
      }
      
      int BinarySearchTree::GetNodesCount(const node* ptr) const
      {
      	if (!ptr) return 0;
      	else return GetNodesCount(ptr->left) + 1 + GetNodesCount(ptr->right);
      }
      
      int BinarySearchTree::GetMaxDepth() const
      {
      	const node* root = tree;
      	return GetMaxDepth(root);
      }
      
      int BinarySearchTree::GetMaxDepth(const node* ptr) const
      {
      	if (!ptr) return 0;
      
      	int left_depth = GetMaxDepth(ptr->left);
      	int right_depth = GetMaxDepth(ptr->right);
      
      	return std::max(left_depth, right_depth) + 1;
      }
      
      int BinarySearchTree::GetMinDepth() const
      {
      	const node* root = tree;
      	return GetMinDepth(root);
      }
      
      int BinarySearchTree::GetMinDepth(const node* ptr) const
      {
      	if (!ptr) return 0;
      
      	int left_depth = GetMaxDepth(ptr->left);
      	int right_depth = GetMaxDepth(ptr->right);
      
      	return std::min(left_depth, right_depth) + 1;
      }
      
      /*bool BinarySearchTree::IsBinaryBalanceTree() const
      {
      	const node* root = tree;
      	return IsBinaryBalanceTree(root);
      }
      
      bool BinarySearchTree::IsBinaryBalanceTree(const node* ptr) const
      {
      	// TODO: code need to modify
      	if (GetMaxDepth(ptr) - GetMinDepth(ptr) <= 1) return true;
      	else return false;	
      }*/
      
      int BinarySearchTree::GetMinValue(info& data) const
      {
      	if (!tree) {
      		fprintf(stderr, "Error: it is a empty tree\n");
      		return -1;
      	}
      
      	const node* root = tree;
      	while (root->left) root = root->left;
      	data = root->data;
      
      	return 0;
      }
      
      int BinarySearchTree::GetMaxValue(info& data) const
      {
      	if (!tree) {
      		fprintf(stderr, "Error: it is a empty tree\n");
      		return -1;
      	}
      
      	const node* root = tree;
      	while (root->right) root = root->right;
      	data = root->data;
      
      	return 0;
      }
      
      int BinarySearchTree::Delete(int id)
      {
      	if (!tree) {
      		fprintf(stderr, "Error: it is a empty tree\n");
      		return -1;
      	}
      
      	const node* root = tree;
      	const node* ret = Search(root, id);
      	if (!ret) {
      		fprintf(stdout, "Warning: this id don't exist in the tree: %d", id);
      		return 0;
      	}	
      
      	tree = Delete(tree, id);	
      
      	return 0;
      }
      
      node* BinarySearchTree::GetMinValue(node* ptr)
      {
      	node* tmp = ptr;
      	while (tmp->left) tmp = tmp->left;
      
      	return tmp;
      }
      
      node* BinarySearchTree::Delete(node* ptr, int id)
      {
      	if (!ptr) return ptr;
      
      	if (id < ptr->data.id)
      		ptr->left = Delete(ptr->left, id);
      	else if (id > ptr->data.id) 
      		ptr->right = Delete(ptr->right, id);
      	else {
      		if (!ptr->left) {
      			node* tmp = ptr->right;
      			delete ptr;
      			return tmp;
      		} else if (!ptr->right) {
      			node* tmp = ptr->left;
      			delete ptr;
      			return tmp;
      		}
      
      		node* tmp = GetMinValue(ptr->right);
      		ptr->data = tmp->data;
      		ptr->right = Delete(ptr->right, tmp->data.id);
      	}
      
      	return ptr;	
      }
      
      int BinarySearchTree::SaveTree(const char* name) const
      {
      	std::ofstream file(name, std::ios::out);
      	if (!file.is_open()) {
      		fprintf(stderr, "Error: open file fail: %s\n", name);
      		return -1;
      	}
      
      	const node* root = tree;
      	int max_depth = GetMaxDepth(root);
      	int max_nodes = (1 << max_depth) -1;
      	root = tree;
      	int nodes_count = GetNodesCount(root);
      	//fprintf(stdout, "max_depth: %d, max nodes: %d\n", max_depth, max_nodes);
      	file<<nodes_count<<","<<max_depth<<std::endl;
      	std::vector<row> vec(max_nodes, std::make_tuple(-1, -1, " ", -1, " "));
      	root = tree;
      	NodeToRow(root, vec, 0);	
      
      	for (const auto& v : vec) {
      		file << std::get<0>(v)<<","<<std::get<1>(v)<<","<<std::get<2>(v)<<","<<std::get<3>(v)<<","<<std::get<4>(v)<<std::endl;
      	}
      
      	file.close();
      	return 0;
      }
      
      void BinarySearchTree::NodeToRow(const node* ptr, std::vector<row>& rows, int pos) const
      {
      	if (!ptr) return;
       	
      	rows[pos] = std::make_tuple(0, ptr->data.id, ptr->data.name, ptr->data.age, ptr->data.addr);
      
      	if (ptr->left) NodeToRow(ptr->left, rows, 2 * pos + 1);
      	if (ptr->right) NodeToRow(ptr->right, rows, 2 * pos + 2);
      }
      
      int BinarySearchTree::LoadTree(const char* name)
      {
      	std::ifstream file(name, std::ios::in);
      	if (!file.is_open()) {
      		fprintf(stderr, "Error: open file fail: %s\n", name);
      		return -1;
      	}
      
      	std::string line, cell;
      	std::getline(file, line);
      	std::stringstream line_stream(line);
      	std::vector<int> vec;
      	while (std::getline(line_stream, cell, ',')) {
      		vec.emplace_back(std::stoi(cell));
      	}
      	if (vec.size() != 2) {
      		fprintf(stderr, "Error: parse txt file fail\n");
      		return -1;
      	}
      	fprintf(stdout, "nodes count: %d, max depth: %d\n", vec[0], vec[1]);
      
      	int max_nodes = (1 << vec[1]) - 1;
      	std::vector<row> rows;
      
      	while (std::getline(file, line)) {
      		std::stringstream line_stream2(line);
      		std::vector<std::string> strs;
      		while (std::getline(line_stream2, cell, ',')) {
      			strs.emplace_back(cell);
      		}
      		if (strs.size() != 5) {
      			fprintf(stderr, "Error: parse line fail\n");
      			return -1;
      		}
      
      		row tmp = std::make_tuple(std::stoi(strs[0]), std::stoi(strs[1]), strs[2], std::stoi(strs[3]), strs[4]);
      		rows.emplace_back(tmp);
      	}
      
      	if (rows.size() != max_nodes || std::get<0>(rows[0]) == -1) {
      		fprintf(stderr, "Error: parse txt file line fail\n");
      		return -1;
      	}
      
      	node* root = new node;
      	root->data = {std::get<1>(rows[0]), std::get<2>(rows[0]), std::get<3>(rows[0]), std::get<4>(rows[0])};
      	root->left = nullptr;
      	root->right = nullptr;
      	tree = root;
      
      	RowToNode(root, rows, max_nodes, 0);
      
      	file.close();
      	return 0;
      }
      
      void BinarySearchTree::RowToNode(node* ptr, const std::vector<row>& rows, int n, int pos)
      {
      	if (!ptr || n == 0) return;
      
      	int new_pos = 2 * pos + 1;
      	if (new_pos < n && std::get<0>(rows[new_pos]) != -1) {
      		ptr->left = new node;
      		ptr->left->data = {std::get<1>(rows[new_pos]), std::get<2>(rows[new_pos]), std::get<3>(rows[new_pos]), std::get<4>(rows[new_pos])};
      		ptr->left->left = nullptr;
      		ptr->left->right = nullptr;
      
      		RowToNode(ptr->left, rows, n, new_pos);
      	}
      
      	new_pos = 2 * pos + 2;
      	if (new_pos < n && std::get<0>(rows[new_pos]) != -1) {
      		ptr->right = new node;
      		ptr->right->data = {std::get<1>(rows[new_pos]), std::get<2>(rows[new_pos]), std::get<3>(rows[new_pos]), std::get<4>(rows[new_pos])};
      		ptr->right->left = nullptr;
      		ptr->right->right = nullptr;
      
      		RowToNode(ptr->right, rows, n, new_pos);
      	}	
      }
      
      
      int test_binary_search_tree()
      {
      	fprintf(stdout, "create binary search tree:\n");
      	std::vector<info> infos{{1004, "Tom", 8, "Beijing"}, {1005, "Jack", 9, "Tianjin"}, {1003, "Mark", 6, "Hebei"}, {1009, "Lisa", 11, "Beijiing"}, {1007, "Piter", 4, "Hebei"}, {1001, "Viner", 6, "Beijing"}};
      
      	BinarySearchTree bstree;
      	bstree.Init(infos);
      	
      	fprintf(stdout, "\ninsert operation:\n");
      	std::vector<info> infos2{{1007, "xxx", 11, "yyy"}, {1008, "Lorena", 22, "Hebie"}, {1002, "Eillen", 14, "Shanxi"}};
      	for (const auto& info : infos2) {
      		int flag = bstree.Insert(info);
      		if (flag) fprintf(stdout, "insert success\n");
      		else fprintf(stdout, "Warning: id %d already exists, no need to insert\n", info.id);
      	}
      
      	fprintf(stdout, "\ntraversal operation:\n");
      	fprintf(stdout, "pre-order traversal:\n");
      	bstree.Traversal(0);
      	fprintf(stdout, "in-order traversal:\n");
      	bstree.Traversal(1);
      	fprintf(stdout, "post-order traversal:\n");
      	bstree.Traversal(2);
      	fprintf(stdout, "level traversal:\n");
      	bstree.Traversal(3);
      
      	fprintf(stdout, "\nsearch operation:\n");
      	std::vector<int> ids {1009, 2000};
      	for (auto id : ids) {
      		info ret;
      		bool flag = bstree.Search(id, ret);
      		if (flag)
      			fprintf(stdout, "found: info: %d, %s, %d, %s\n", ret.id, ret.name.c_str(), ret.age, ret.addr.c_str());
      		else
      			fprintf(stdout, "no find: no id info: %d\n", id);
      	}
      
      	fprintf(stdout, "\nwhether or not is a binary search tree operation:\n");
      	bool flag2 = bstree.IsBinarySearchTree();
      	if (flag2) fprintf(stdout, "it is a binary search tree\n");
      	else fprintf(stdout, "it is not a binary search tree\n");
      
      	fprintf(stdout, "\ncalculate node count operation:\n");
      	int count = bstree.GetNodesCount();
      	fprintf(stdout, "tree node count: %d\n", count);
      	
      	fprintf(stdout, "\ncalculate tree depth operation:\n");
      	int max_depth = bstree.GetMaxDepth();
      	int min_depth = bstree.GetMinDepth();
      	fprintf(stdout, "tree max depth: %d, min depth: %d\n", max_depth, min_depth);
      	
      	/*fprintf(stdout, "\nwhether or not is a binary balance tree operation:\n");
      	flag2 = bstree.IsBinaryBalanceTree();
      	if (flag2) fprintf(stdout, "it is a binary balance tree\n");
      	else fprintf(stdout, "it is not a binary balance tree\n");*/
      	
      	fprintf(stdout, "\nget min and max value(id):\n");
      	info value;
      	bstree.GetMinValue(value);
      	fprintf(stdout, "tree min value: id: %d\n", value.id);
      	bstree.GetMaxValue(value);
      	fprintf(stdout, "tree max value: id: %d\n", value.id);
      
      	fprintf(stdout, "\ndelete node operation:\n");
      	bstree.Delete(1005);
      	bstree.Traversal(1);
      
      	fprintf(stdout, "\nsave tree operation:\n");
      #ifdef _MSC_VER
      	char* name = "E:/GitCode/Messy_Test/testdata/binary_search_tree.model";
      #else
      	char* name = "testdata/binary_search_tree.model";
      #endif
      	bstree.SaveTree(name);
      
      	fprintf(stdout, "\nload tree operation:\n");
      	BinarySearchTree bstree2;
      	bstree2.LoadTree(name);
      	int count2 = bstree2.GetNodesCount();
      	int max_depth2 = bstree2.GetMaxDepth();
      	int min_depth2 = bstree2.GetMinDepth();
      	fprintf(stdout, "tree node count: %d, tree max depth: %d, min depth: %d\n", count2, max_depth2, min_depth2);
      	bstree2.Traversal(1);
      
      	return 0;
      }
      
      } // namespace binary_search_tree_
      

      支持Linux和Windows直接编译,Windows通过VS,linux下执行prj/linux_cmake_CppBaseTest/build.sh脚本。执行结果如下:

      保存的binary_search_tree.model结果如下:

      7,4
      0,1004,Tom,8,Beijing
      0,1003,Mark,6,Hebei
      0,1009,Lisa,11,Beijiing
      0,1001,Viner,6,Beijing
      -1,-1, ,-1, 
      0,1007,Piter,4,Hebei
      -1,-1, ,-1, 
      -1,-1, ,-1, 
      0,1002,Eillen,14,Shanxi
      -1,-1, ,-1, 
      -1,-1, ,-1, 
      -1,-1, ,-1, 
      0,1008,Lorena,22,Hebie
      -1,-1, ,-1, 
      -1,-1, ,-1, 
      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.csdn.net/fengbingchun/article/details/83239268,作者:fengbingchun,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:Python解析XML示例与解释

      下一篇:Java观察者模式 : Observer / Observable

      相关文章

      2025-05-19 09:04:14

      二叉树经典OJ练习

      二叉树经典OJ练习

      2025-05-19 09:04:14
      root , 二叉树 , 子树 , 节点 , 遍历
      2025-05-19 09:04:14

      《剑指Offer》按之字形顺序打印二叉树——最容易理解的思路,两分钟学会~

      《剑指Offer》按之字形顺序打印二叉树——最容易理解的思路,两分钟学会~

      2025-05-19 09:04:14
      二叉树 , 数据结构
      2025-05-19 09:04:14

      《剑指Offer》二叉搜索树的第k个节点——真没你想象中那么难,一招教你秒杀它~

      《剑指Offer》二叉搜索树的第k个节点——真没你想象中那么难,一招教你秒杀它~

      2025-05-19 09:04:14
      二叉树 , 数据结构
      2025-05-13 09:50:28

      翻转二叉树,​​101. 对称二叉树​

      翻转二叉树给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

      2025-05-13 09:50:28
      Node , root , val , 二叉树 , 翻转 , 节点
      2025-05-13 09:50:28

      翻转二叉树-对称二叉树

      给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

      2025-05-13 09:50:28
      right , 二叉树 , 左子 , 节点 , 遍历
      2025-05-13 09:50:17

      二叉树的中序遍历

      给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

      2025-05-13 09:50:17
      Node , root , val , 二叉树 , 节点 , 遍历
      2025-05-13 09:50:17

      二叉树展开为链表

      二叉树展开为链表

      2025-05-13 09:50:17
      二叉树 , 单链 , 指针 , 结点 , 链表
      2025-05-12 10:19:12

      DS初阶:二叉树经典OJ题(1)

      DS初阶:二叉树经典OJ题(1)                                                      

      2025-05-12 10:19:12
      个数 , 二叉树 , 结点 , 节点 , 解析 , 遍历
      2025-05-12 10:19:12

      DFS:二叉树的深搜与回溯

      DFS:二叉树的深搜与回溯

      2025-05-12 10:19:12
      LeetCode , path , 二叉树 , 力扣 , 思路 , 节点 , 路径
      2025-05-12 09:10:14

      从前序与中序遍历序列构造二叉树,437. 路径总和 III

      给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。

      2025-05-12 09:10:14
      lt , 二叉树 , 节点
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5253972

      查看更多

      最新文章

      【C/C++笔记】:易错难点3 (二叉树)

      2025-05-07 09:09:52

      数据结构 二叉树后序遍历 C语言

      2025-05-07 09:08:42

      C++Lambda表达式

      2025-05-07 09:08:42

      数据结构 二叉树层次遍历 C语言

      2025-05-07 09:08:42

      C++小技巧---CString 转 double

      2025-04-23 08:18:32

      【数据结构】遍历二叉树(递归思想)-->赋源码

      2025-04-22 09:27:37

      查看更多

      热门文章

      C++最普通的定时器功能实现

      2023-03-08 10:27:24

      C/C++泛型编程实现数据结构之栈

      2023-05-15 10:00:33

      C++生成指定范围内随机数封装

      2023-02-07 10:34:04

      C++中substr函数的用法

      2023-04-18 14:14:13

      C++拷贝构造函数(深拷贝,浅拷贝)详解

      2023-03-30 09:59:46

      C++入门篇之C++ 指针

      2023-03-14 11:26:53

      查看更多

      热门标签

      java Java python 编程开发 代码 开发语言 算法 线程 Python html 数组 C++ 元素 javascript c++
      查看更多

      相关产品

      弹性云主机

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

      天翼云电脑(公众版)

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

      对象存储

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

      云硬盘

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

      查看更多

      随机文章

      C++ new和malloc区别

      C++——拷贝构造和运算符重载

      C++学习007-使用exit退出进程

      Essential C++ 第7章 异常处理

      C++ 深拷贝和浅拷贝

      1083 是否存在相等的差 (20 分)

      • 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号