数据结构第八章 二叉搜索树

//二叉排序树(二叉搜索树,二叉查找树)

//二叉树-》》》》bst

//1,对于一个节点,如果他有左子树,左子树都比他小

//2.对于右子树,右子树都比他大

#include

using namespace std;

template

class treesort

{

private:

struct node

{

T data;

node *left;

node *right;

};

复制代码
node *root;

public:

treesort(T dataroot)

{

auto temp=new node;

temp->data=dataroot;

root=temp;

root->left=nullptr;

root->right=nullptr;

}

复制代码
node* find(node *root,T x)
{
	if(root==nullptr)
		return root;
	if(root->data==x)
	{
		return root;
	}
	if(x<root->data)
	{
		return find(root->left,x);
	}
	if(x>root->data)
	{
		return find(root->right,x);
	}
	return nullptr;
}

void insert(T dataa)
{
	node** cur = &root;           // 从根指针的地址开始
	while (*cur != nullptr)
	{
		if (dataa == (*cur)->data)
			return;               // 已存在,不插入
		else if (dataa < (*cur)->data)
			cur = &((*cur)->left);
		else
			cur = &((*cur)->right);
	}
	// 此时 *cur 正好是父节点中指向该空位的指针(左或右)
	*cur = new node{dataa, nullptr, nullptr};
}

void print(node* root)
{
	if(root==nullptr)
		return;
	if(root->left!=nullptr)
	print(root->left);
	cout<<root->data<<" ";
	if(root->right!=nullptr)
	print(root->right);
}

node* getroot()
{
	return root;
}

};

int main()

{

int as;

cin>>as;

treesort run(as);

int n;

cin>>n;

while(n--)

{

int k;

cin>>k;

run.insert(k);

}

run.print(run.getroot());

return 0;

}

相关推荐
漂流瓶jz23 分钟前
UVA-1442 洞穴 题解答案代码 算法竞赛入门经典第二版
c++·算法·题解·aoapc·算法竞赛入门经典·uva
叠层归一研究院2 小时前
基于极限自指的叠层归一宇宙结构理论——无元外部封闭系统的内生区分模型
人工智能·经验分享·算法·agi
Selvaggia3 小时前
Diffusion Model 的基本原理与模型架构
算法
wabs6664 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
hanlin034 小时前
刷题笔记:力扣第41题-缺失的第一个正数
笔记·算法·leetcode
shehuiyuelaiyuehao5 小时前
算法50,分治归并,数组中的逆序对
java·算法
阳明山水5 小时前
校准分位数驱动智能库存决策
人工智能·深度学习·算法·机器学习·架构
雨落在了我的手上6 小时前
Java数据结构(十四):Map和Set
数据结构
码行山野赴时序归途6 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
别动我齐刘海6 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人