BST(binary search tree)

本文介绍了一种使用C++实现二叉搜索树的方法,并提供了插入和查找元素的完整代码示例。通过递归的方式实现了节点的插入和查找功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;

typedef struct node *link;
struct node{
	int value;
	link l;
	link r;
	int count;
};

static link head,z;

link NEW(int value,link l,link r,int count)
{
	link x = new node;
	x->count = count;
	x->l = l;
	x->r = r;
	x->value = value;

	return x;
}

void init()
{
	head = (z=NEW(0,0,0,0));
}

int getCount()
{
	return head->count;
}

int Search(link h,int key)
{
	if(h==z){
		cout<<"tree is null"<<endl;
		exit(-1);
	}

	if(key < h->value){
		return Search(h->l,key);
	}
	else if(key > h->value){
		return Search(h->r,key);
	}else
	{
		return h->value;
	}
}


link Insert(link h,int key)
{
	if(h==z){
		return NEW(key,z,z,1);
	}

	if(h->value > key)
	{
		h->l = Insert(h->l,key); 
	}
	else{
		h->r = Insert(h->r,key);
	}

	h->count++;

	return h;
}

int main()
{
	init();
	srand(time(0));

	for(int i=1;i<=15;i++)
	{
		head = Insert(head,i);
		//这个不能直接写成Insert(head,i);
	}

	cout<<endl;

	cout<<getCount()<<endl;

	for(i=0;i<15;i++)
	{
		cout<<Search(head,i)<<" ";
	}

	cout<<endl;

	return 0;
}


#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;

typedef struct node *link;
struct node{
	int value;
	link l;
	link r;
	int count;
};

static link head,z;

link NEW(int value,link l,link r,int count)
{
	link x = new node;
	x->count = count;
	x->l = l;
	x->r = r;
	x->value = value;

	return x;
}

void init()
{
	head = (z=NEW(0,0,0,0));
}

int getCount()
{
	return head->count;
}

int Search(link h,int key)
{
	if(h==z){
		cout<<"tree is null"<<endl;
		exit(-1);
	}

	if(key < h->value){
		return Search(h->l,key);
	}
	else if(key > h->value){
		return Search(h->r,key);
	}else
	{
		return h->value;
	}
}


link Insert(link h,int key)
{
	if(h==z){
		return NEW(key,z,z,1);
	}

	if(h->value > key)
	{
		h->l = Insert(h->l,key); 
	}
	else{
		h->r = Insert(h->r,key);
	}

	h->count++;

	return h;
}


link Insert_v1(link &h,int key)
{
	link p,x;
	int y=0;

	if(h==z){
		return (h=NEW(key,z,z,1));
	}

	x=h;
    p=h;

	while(x!=z)
	{
		p=x;
		x->count++;
		if(key>x->value){
			x=x->r;
		}
		else{
			x=x->l;
		}
	
	}

	x = NEW(key,z,z,1);
	if(key > p->value){
		p->r = x;
	}
	else{
		p->l = x;
	}

	return h;
}

int main()
{
	init();
	srand(time(0));

	for(int i=1;i<=15;i++)
	{
		head = Insert_v1(head,i);
		//head = Insert(head,i);
	}

	cout<<getCount()<<endl;

	for(i=1;i<=15;i++)
	{
		cout<<Search(head,i)<<" ";
	}

	cout<<endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值