二叉搜索树

本文介绍了一种使用C++实现二叉搜索树的方法,包括插入元素和搜索元素的功能。通过递归的方式实现了节点的创建与查找,适用于数据结构的学习与实践。

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

#include<iostream>
using namespace std;
int a[100],n=10;
struct Node{
int key;
Node *left;
Node *right;
};
bool Insert(Node *&p,int element){
if(p==NULL){
p=new Node;
p->key=element;
p->left=p->right=NULL;
return true;
}


if(element<p->key)
return Insert(p->left,element);
else return Insert(p->right,element);
}
void create(Node *&T,int n){
T=NULL;
for(int i=0;i<n;i++){
Insert(T,a[i]);
}
}
bool Search(Node *&T,int x){
Node*p=T;
while(p!=NULL&&x!=p->key){
if(x>p->key)
p=p->right;
else p=p->left;
}
if(p==NULL)
return false;
else return true;
}
bool Search_n(Node*&T,int x){
Node *p=T;
if(p==NULL)return false;
if(x==T->key)return true;
else if(x<T->key)return Search_n(T->left,x);
else return Search_n(T->right,x);}
int main(){
for (int i=0;i<n;i++)
cin>>a[i];
Node *T=NULL;
create(T,n);
Node *p=NULL;
int x;
cin>>x;
if(Search(T,x))
cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值