BST(二叉搜索树)的基本知识

比较简单来讲的话,BST就是根结点的左子树所有的结点值都要小于根结点的值
根结点右子树所有结点的值都要大于根结点的值
比较重要的就是插入和创建树和查找,其中创建树是通过查找来实现的
其余的操作都和普通的二叉树差不多

#include <bits/stdc++.h>
using namespace std;


struct node
{
	int val;
	node* lchild;
	node* rchild;
	node(int a)
	{
		val=a;
		lchild=NULL;
		rchild=NULL;
	}
	node()
	{
		val=0;
		lchild=NULL;
		rchild=NULL;
	}
};

void insert(node*& root,int x)
{
	if(root==NULL)
	{
		root=new node(x);
		return ;
	}
	if(x==root->val)//在创建的时候这样可以确保不会重复,当然可以不要,根据具体的题目而定 
	{
		return ;
	}
	else if(x<root->val)
	{
		insert(root->lchild,x);
	}
	else
	{
		insert(root->rchild,x);
	}
}

node* createTree(int data[],int n)
{
	node* root=NULL;
	for(int i=0;i<n;i++)
	{
		insert(root,data[i]);
	}
	return root;
} 

void inOrder(node* root)
{
	if(root==NULL)
	{
		return;
	}
	inOrder(root->lchild);
	cout<<root->val<<" ";
	inOrder(root->rchild);
}

void search(node* root,int x)//和插入差不多
{
	if(root==NULL)
	{
		cout<<x<<" search failed"<<endl;
		return ;
	}
	if(x==root->val)
	{
		cout<<root->val;
	}
	else if(x<root->val)
	{
		search(root->lchild,x);	
	}
	else
	{
		search(root->rchild,x);
	}
}


int main()
{
	int data[10]={1,2,3,4,5,6,7,8,9,0};
	int n=10;
	node* root=createTree(data,n);
	inOrder(root);
	cout<<endl;
	search(root,9);
	cout<<endl;
	search(root,10);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值