欢迎来到天天文库
浏览记录
ID:20501212
大小:25.00 KB
页数:6页
时间:2018-10-13
《二叉排序树查找》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#include#defineINFMT"%d"#defineOUTFMT"%d"/*#defineNULL0L*/#defineBOOLint#defineTRUE1#defineFALSE0#defineLEN10000typedefintElemType;typedefstructBSTNode{ElemTypedata;structBSTNode*lchild,*rchild;}BSTNode,*BSTree;/*插入新节点*/voidInsert(BSTree*tree
2、,ElemTypeitem){BSTreenode=(BSTree)malloc(sizeof(BSTNode));node->data=item;node->lchild=node->rchild=NULL;if(!*tree)*tree=node;else{BSTreecursor=*tree;while(1){if(itemdata){if(NULL==cursor->lchild){cursor->lchild=node;break;}cursor=cursor->lchild;}else{if(NULL==cursor->rchild)
3、{cursor->rchild=node;break;}cursor=cursor->rchild;}}}return;}/*查找指定值*/BSTreeSearch(BSTreetree,ElemTypeitem){BSTreecursor=tree;while(cursor){if(item==cursor->data)returncursor;elseif(itemdata)cursor=cursor->lchild;elsecursor=cursor->rchild;}returnNULL;}/*中缀遍历*/voidInorder(BSTr
4、eetree){BSTreecursor=tree;if(cursor){Inorder(cursor->lchild);printf(OUTFMT,cursor->data);Inorder(cursor->rchild);}}/*回收资源*/voidCleanup(BSTreetree){BSTreecursor=tree,temp=NULL;if(cursor){Cleanup(cursor->lchild);Cleanup(cursor->rchild);free(cursor);}}/*产生一组随机数*/voidrandnum(int*a,ints){i
5、nti,j,mod=s*10;srand(time(NULL));for(i=0;i
6、intf("1.手动输入数据创建二叉排序树");printf("2.自动产生数据创建二叉排序树");do{scanf("%c",&choice);getchar();if(choice=='1'
7、
8、choice=='2')finish=TRUE;}while(FALSE==finish);switch(choice){case'1':{printf("请输入数据(-10000结束):");while(1){scanf(INFMT,&item);if(-10000!=item)Insert(&root,item);elsebreak;}break;}ca
9、se'2':{intia[LEN],i=0,loop=LEN;randnum(ia,LEN);while(loop--){Insert(&root,ia[i++]);}break;}}printf("创建完成...");Inorder(root);printf("");/*二叉排序树的查找测试*/do{printf("请输入查找数据:");scanf("%d",&item);getchar();printf("Searching...");ret=Search(root,item);if(NULL==ret)printf("查找失败!"
10、);els
此文档下载收益归作者所有