1. 程式人生 > >swust oj 1011

swust oj 1011

std ont ring find lock lse mes arr ret

二叉排序樹的實現和查找

1000(ms) 10000(kb) 2782 / 6301 按照給定的關鍵字集合,建立二叉排序樹。在建立的二叉排序樹上查找指定的關鍵字,查找成功,輸出找到該關鍵字比較的次數;查找不成功,輸出-1.

輸入

關鍵字個數n; 
關鍵字集合; 
要查找的關鍵字;

輸出

查找成功輸出比較的次數,否則輸出-1。

樣例輸入

12
25 18 46 2 53 39 32 4 74 67 60 11
74

樣例輸出

4

 1 #include<iostream>
 2 #include<algorithm>
 3
#include<cstring> 4 #include<cstdlib> 5 #include<cstdio> 6 typedef int Datetype; 7 using namespace std; 8 int x; 9 10 typedef struct link{ 11 Datetype date; 12 struct link *lchild; 13 struct link *rchild; 14 }tree; 15 16 void creat(tree *&L, int
arr[] ,int l,int r) 17 { 18 if(l>r) 19 { 20 L=NULL; 21 return ; 22 } 23 int s=(l+r)>>1; 24 L=new tree; 25 L->date=arr[s]; 26 creat(L->lchild,arr,l,s-1); 27 creat(L->rchild,arr,s+1,r); 28 } 29 30 void display(tree *&L)
31 { 32 if(L!=NULL) 33 { 34 cout<<L->date<<" "; 35 display(L->lchild); 36 display(L->rchild); 37 } 38 } 39 40 void delet(tree *&L) 41 { 42 if(L!=NULL) 43 { 44 delet(L->lchild); 45 delet(L->rchild); 46 delete(L); 47 } 48 } 49 50 void find(tree *&L, int a) 51 { 52 if(L!=NULL) 53 { 54 x++; 55 if(a>L->date) 56 find(L->rchild,a); 57 else if(a<L->date) 58 find(L->lchild,a); 59 else 60 return ; 61 } 62 if(L==NULL) 63 x=0; 64 } 65 66 int main() 67 { 68 int arr[100]; 69 int n,a; 70 tree *L; 71 cin>>n; 72 for(int i=0;i<n;i++) 73 { 74 cin>>arr[i]; 75 } 76 sort(arr,arr+n); 77 cin>>a; 78 creat(L,arr,0,n-1); 79 // display(L); 80 find(L,a); 81 if(x) 82 cout<<x; 83 else 84 cout<<"-1"; 85 delet(L); 86 return 0; 87 }

swust oj 1011