欢迎来到天天文库
浏览记录
ID:37715462
大小:24.87 KB
页数:4页
时间:2019-05-29
《二叉查找数的建立,删除,查找算法》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、试验代码://创ä¡ä建¡§二t叉?排?序¨°树º¡Âtypedefstructbst{intdata;structbst*left;structbst*right;}BSTree;intsource[]={54,90,6,69,12,37,92,28,65,83};//insertakeyvoidInsertBST(BSTree*t,intkey){BSTree*p,*parent,*head;if(!(p=(BSTree*)malloc(sizeof(BSTree*)))){cout<<"failedtoalloct!"<2、ndl;exit(0);}p->data=key;p->left=p->right=NULL;head=t;while(head){parent=head;if(keydata)head=head->left;elsehead=head->right;}if(keydata)parent->left=p;elseparent->right=p;}//creatatreevoidCreatBST(BSTree*t,intdata[],intn){t->data=data[0];t->left=t->r3、ight=NULL;for(inti=1;ileft);cout<data<<"";BST_LDR(t->right);}}//searchthekeyinthetreeBSTree*SearchBST(BSTree*t,intkey){if(!t4、5、t->data==key)returnt;elseif(keydata)return(SearchBST(6、t->left,key));elsereturn(SearchBST(t->right,key));}//deleteavalueinthetreevoidBST_Delete(BSTree*t,intkey){BSTree*p,*parent,*l,*ll;intchild=0;if(!t)return;p=t;parent=p;while(p){if(p->data==key){if(!p->left&&!p->right){if(p==t)free(p);elseif(child==0){parent->left=NULL;7、free(p);}else{parent->right=NULL;free(p);}}elseif(!p->left){if(child==0)parent->left=p->right;elseparent->left=p->left;//????free(p);}elseif(!p->right){if(child==0)parent->right=p->right;elseparent->right=p->left;free(p);}else{ll=p;l=p->right;while(l->left){ll=l;l=l->8、left;}p->data=l->data;ll->data=NULL;free(ll);}p=NULL;}elseif(keydata){child=0;parent=p;p=p->left;}else{child=1;parent=p;p=p->right;}}}主函数调用为:#include"stdafx.h"#include"example33.h"intmain(){BSTreebst,*pos;CreatBST(&bst,source,10);cout<<"theresultofscanthetreeis:"<9、data<
2、ndl;exit(0);}p->data=key;p->left=p->right=NULL;head=t;while(head){parent=head;if(keydata)head=head->left;elsehead=head->right;}if(keydata)parent->left=p;elseparent->right=p;}//creatatreevoidCreatBST(BSTree*t,intdata[],intn){t->data=data[0];t->left=t->r
3、ight=NULL;for(inti=1;ileft);cout<data<<"";BST_LDR(t->right);}}//searchthekeyinthetreeBSTree*SearchBST(BSTree*t,intkey){if(!t
4、
5、t->data==key)returnt;elseif(keydata)return(SearchBST(
6、t->left,key));elsereturn(SearchBST(t->right,key));}//deleteavalueinthetreevoidBST_Delete(BSTree*t,intkey){BSTree*p,*parent,*l,*ll;intchild=0;if(!t)return;p=t;parent=p;while(p){if(p->data==key){if(!p->left&&!p->right){if(p==t)free(p);elseif(child==0){parent->left=NULL;
7、free(p);}else{parent->right=NULL;free(p);}}elseif(!p->left){if(child==0)parent->left=p->right;elseparent->left=p->left;//????free(p);}elseif(!p->right){if(child==0)parent->right=p->right;elseparent->right=p->left;free(p);}else{ll=p;l=p->right;while(l->left){ll=l;l=l->
8、left;}p->data=l->data;ll->data=NULL;free(ll);}p=NULL;}elseif(keydata){child=0;parent=p;p=p->left;}else{child=1;parent=p;p=p->right;}}}主函数调用为:#include"stdafx.h"#include"example33.h"intmain(){BSTreebst,*pos;CreatBST(&bst,source,10);cout<<"theresultofscanthetreeis:"<
9、data<
此文档下载收益归作者所有