break;
}
}
}
2.2.6二叉树查询函数
上文二叉树基本函数中的SearchBST()即为二叉树查询函数。
3数据测试与结果
3.1实现二叉树生成、插入、删除及前中后根遍历
3.1.1测试主函数
voidmain()
{
intnlayer;
BiTreeBT,p;
BT=NULL;
p=NULL;
nlayer=1;
ElemTypee,d;
CreateBST(BT,p);
printf("二叉排序树树形输出为:
\n");
DispalyBST(BT,nlayer);
printf("请输入插入的元素:
");
scanf_s("%d",&e.key);
InsertBST(BT,e);
printf("\n");
DispalyBST(BT,nlayer);
printf("请输入删除的元素:
");
scanf_s("%d",&d.key);
DeleteBST(BT,d.key);
printf("\n");
DispalyBST(BT,nlayer);
printf("先序遍历为:
");
PreOrderTraverse(BT,Visit);
printf("\n中序遍历为:
");
InOrderTraverse(BT,Visit);
printf("\n后序遍历为:
");
PostOrderTraverse(BT,Visit);
ClearBiTree(BT);
printf("\n二叉排序树已清空.\n");
DispalyBST(BT,nlayer);
DestroyBiTree(BT);
printf("\n二叉排序树已销毁.\n");
system("pause");
}
3.1.2测试结果截图
3.2对比二叉排序树查询和数组查询的效率
3.2.1测试主函数
voidmain()
{
intnlayer,key,length;
clock_tstart,finish;
BiTreeBT,p;
doubleduration;
BT=NULL;
p=NULL;
nlayer=1;
ElemTypea[]={51,"陈继真",88,
82,"黄景元",89,
53,"贾成",88,
44,"呼颜",90,
25,"鲁修德",88,
56,"须成",88,
47,"孙祥",87,
38,"柏有患",89,
9,"革高",89,
10,"考鬲",87,
31,"李燧",86,
12,"夏祥",89,
53,"余惠",84,
4,"鲁芝",90,
75,"黄丙庆",88,
16,"李应",89,
87,"杨志",86,
18,"李逵",89,
9,"阮小五",85,
20,"史进",88,
21,"秦明",88,
82,"杨雄",89,
23,"刘唐",85,
64,"武松",88,
25,"李俊",88,
86,"卢俊义",88,
27,"华荣",87,
28,"杨胜",88,
29,"林冲",89,
70,"李跃",85,
31,"蓝虎",90,
32,"宋禄",84,
73,"鲁智深",89,
34,"关斌",90,
55,"龚成",87,
36,"黄乌",87,
57,"孔道灵",87,
38,"张焕",84,
59,"李信",88,
30,"徐山",83,
41,"秦祥",85,
42,"葛公",85,
23,"武衍公",87,
94,"范斌",83,
45,"黄乌",60,
67,"叶景昌",99,
7,"焦龙",89,
78,"星姚烨",85,
49,"孙吉",90,
60,"陈梦庚",95,
};
length=sizeof(a)/sizeof(a[0]);
CreateBST(BT,p,a,length);
//树形显示二叉排序树
printf("二叉排序树树形输出为:
\n");
ShowBST(BT,nlayer);
while
(1){
printf("请输入需要查找的学生学号:
\n");
cin>>key;
if(!
key)
break;
//通过二叉树搜索记录
start=clock();
SearchBST(BT,key,NULL,p);
cout<<"学号:
"<data.key<<"姓名:
"<data.name<<"成绩:
"<data.grade<finish=clock();
duration=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<"二叉树查询时间:
"<
//通过数组搜索记录
start=clock();
ArraySearch(a,key,length);
finish=clock();
duration=(double)(finish-start)/CLOCKS_PER_SEC;
cout<<"数组查询时间:
"<}
}
3.2.2测试结果截图
3.2.3结论:
经过三次查询可以看出,二叉树的查找效率要高于数组。
当二叉排序树为满二叉树时,树的查找效率最高,因为二叉排序树的平均查找长度和logn是等数量级的,树的深度越小,查找效率越高。
因此,要提高二叉排序树的查找效率,可以将二叉排序树转变为平衡二叉树。
4总结与改进
4.1总结
通过这次课程设计将栈、链表等基本数据结构和一起实现了一遍,并且了解到,不同数据结构的查找效率是不同的,在选择算法时,不仅要考虑算法实现的难易程度,还要考虑它的效率。
在这次课设中也暴露出了平时练习的不足,自身的编程能力不强,本次很多代码都是参看大神博客直接拿来用的,调bug的时候经常无从入手,需要舍友的帮忙。
编程还是要多练习,看懂理论跟真的实现出来还有很长的距离,理论要应用于实践才能出真知。
4.2改进
改进成平衡二叉树效率可能更高