数据结构实验三二叉树的实现Word文档下载推荐.docx
《数据结构实验三二叉树的实现Word文档下载推荐.docx》由会员分享,可在线阅读,更多相关《数据结构实验三二叉树的实现Word文档下载推荐.docx(8页珍藏版)》请在冰豆网上搜索。
![数据结构实验三二叉树的实现Word文档下载推荐.docx](https://file1.bdocx.com/fileroot1/2022-11/25/51cff535-5abb-490d-bac6-d0e72e057178/51cff535-5abb-490d-bac6-d0e72e0571781.gif)
1.本实验用到的理论知识
2.算法设计
3.编码
生成树编码:
publicclassBiTree{
publicBiTreeNoderoot;
publicBiTree(){
this.root=null;
}
publicBiTree(BiTreeNoderoot){
this.root=root;
}
publicstaticintindex=0;
publicBiTree(StringpreStr){
charc=preStr.charAt(index++);
if(c!
='
#'
){
root=newBiTreeNode(c);
root.lchild=newBiTree(preStr).root;
root.rchild=newBiTree(preStr).root;
}else
root=null;
publicvoidpreRootTraverse(BiTreeNodeT){
if(T!
=null){
System.out.print(T.data);
preRootTraverse(T.lchild);
preRootTraverse(T.rchild);
}
publicvoidpreRootTraverse(){
BiTreeNodeT=root;
LinkStackS=newLinkStack();
S.push(T);
while(!
S.isEmpty()){
T=(BiTreeNode)S.pop();
System.out.print(T.data+"
"
);
while(T!
if(T.lchild!
=null)
System.out.print(T.lchild.data+"
if(T.rchild!
S.push(T.rchild);
T=T.lchild;
}
}
publicvoidinRootTraverse(BiTreeNodeT){
inRootTraverse(T.lchild);
inRootTraverse(T.rchild);
publicvoidineRootTraverse(){
while(S.peek()!
S.push(((BiTreeNode)S.peek()).lchild);
S.pop();
if(!
T=(BiTreeNode)S.pop();
System.out.print(T.data+"
S.push(T.rchild);
publicvoidpostRootTraverse(BiTreeNodeT){
if(T!
=null){
postRootTraverse(T.lchild);
postRootTraverse(T.rchild);
publicvoidpostRootTraverse(){
Booleanflag;
BiTreeNodep=null;
while(!
T=(BiTreeNode)S.peek();
if(T.rchild==null||T.rchild==p){
System.out.print(T.data+"
S.pop();
p=T;
flag=true;
}else{
flag=false;
flag)
break;
}
publicintleafNum(BiTreeNodet){
if(t==null){
return0;
else{
intln=leafNum(t.lchild);
intrn=leafNum(t.rchild);
if(t.lchild==null&
&
t.rchild==null){
returnln+rn+1;
else{
returnln+rn;
publicvoidprintTreeLeaf(BiTreeNodet){
if(t!
printTreeLeaf(t.lchild);
printTreeLeaf(t.rchild);
System.out.print(t.data+"
;
}
}
测试编码:
packagebitree;
importjava.util.Scanner;
publicclassTest{
publicstaticvoidmain(String[]args){
System.out.println("
请输入标明空子树的先根遍历序列:
"
Scannersc=newScanner(System.in);
StringpreStr=sc.next();
BiTreeT=newBiTree(preStr);
System.out.println("
先根遍历输出:
T.preRootTraverse();
System.out.println();
中根遍历输出:
T.ineRootTraverse();
后根遍历输出:
T.postRootTraverse();
叶子节点数"
+T.leafNum(T.root));
System.out.print("
叶子节点:
T.printTreeLeaf(T.root);
4、画出实验中使用的二叉树图形。
(要求每个同学自行设计三个二叉树,节点不少于6个,雷同者本次实验无成绩)
四、运行与调试
1.在调试程序的过程中遇到什么问题,是如何解决的?
问题:
出现字符串索引越界
原因:
二叉树的先根遍历序列错误。
解决办法:
更正为正确的先根序列ACBD###C##。
2.设计了哪些测试数据?
预计结果是什么?
Char数据:
其先根序列分别为
1.1248###59##0##36##7##
2.ABDH##I##E##CFJ###G##
3.12#46#80####35#79#3####
4.abeh##i##dj##b##cfl##m##gn##o##
3.
程序运行的结果如何
五、总结与心得
六、思考题
(1)试将如下森林转为二叉树。
(2)假设用于通讯的电文仅由6个字母组成,字母在电文中出现的频率分别为:
7,9,2,6,32,3。
试为这6个字母设计哈夫曼编码。