二叉搜索树

xiaoxiao2021-02-28  22

#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; }
转载请注明原文地址: https://www.6miu.com/read-2629831.html

最新回复(0)