一、实验目的
1、掌握二叉树的特点及其存储方式;
2、掌握二叉树的创建;
3、掌握二叉树先序、中序、后序遍历的基本方法及应用;
二、实验内容
1、用先序方法建立一棵二叉树;
2、实现先序、中序和后序遍历二叉树的操作;
3、实现统计二叉树叶子结点个数和计算二叉树深度的操作;
三、实验环境
Eclipse环境或C++编程环境
四、实验步骤
1、二叉链表节点类的定义;
2、二叉树类的定义;
3、建立下图所示的二叉树
在以字符串的形式“根左右”定义一棵二叉树时,写出创建二叉树的操作:
4、编程实现以上二叉树的先序、中序和后序遍历操作,输出遍历序列;
5、完成统计以上二叉树中叶子结点的个数或计算以上二叉树的深度;
节点类:
package shiyan2;
public class BiTreeNode {
public Object data;
public BiTreeNode lchild,rchild;
public BiTreeNode() {
this.data=null;
this.lchild=null;
this.rchild=null;
}
public BiTreeNode(Object data) {
this.data=data;
this.lchild=null;
this.rchild=null;
}
public BiTreeNode(Object data,BiTreeNode lchild,BiTreeNode rchild) {
this.data=data;
this.lchild=lchild;
this.rchild=rchild;
}
}
建立二叉树,实现基本操作:
package shiyan2;
public class BiTree {
private BiTreeNode root;
public BiTree() {
this.root=null;
}
public BiTree(BiTreeNode root) {
this.root=root;
}
private static int index=0;//建立一棵二叉树
//使index值不变,加上static改成静态全局变量.若不改的话,每调用一次,index就会清零,那么栈就会一直套下去,最后电脑栈溢出死循环
public BiTree(String preStr) {
char c=preStr.charAt(index++);
if(c!='#') {
root=new BiTreeNode(c);
root.lchild=new BiTree(preStr).root;//在c不为#时,使传进来的字符串依次建立新的节点
root.rchild=new BiTree(preStr).root;
}
else {
root=null;
}
}
public void preRootTraverse(BiTreeNode T) {//先序遍历
if(T!=null) {
System.out.print(T.data);
preRootTraverse(T.lchild);
preRootTraverse(T.rchild);
}
}
public void inRootTraverse(BiTreeNode T) {//中序遍历
if(T!=null) {
inRootTraverse(T.lchild);
System.out.print(T.data);
inRootTraverse(T.rchild);
}
}
public void postRootTraverse(BiTreeNode T) {//后序遍历
if(T!=null) {
postRootTraverse(T.lchild);
postRootTraverse(T.rchild);
System.out.print(T.data);
}
}
public int getLeafNode(BiTreeNode T) {//计算叶子节点的个数
if(T==null) {
return 0;
}
if(T.lchild==null&&T.rchild==null) {
return 1;
}
return getLeafNode(T.lchild)+getLeafNode(T.rchild);
}
public int getDepth(BiTreeNode T) {//获取树的深度
if(T==null) {
return 0;
}
else{
int m=getDepth(T.lchild);
int n=getDepth(T.rchild);
if(m>n)
return m+1;
else
return n+1;
}
}
public static void main(String[] args) {
String preStr="abd###ce##f##";//标明空子树的先根遍历序列
BiTree tree=new BiTree(preStr);//根据标明空子树的先根遍历序列创建一颗树
System.out.println("先根遍历:");
tree.preRootTraverse(tree.root);
System.out.println();
System.out.println("中序遍历:");
tree.inRootTraverse(tree.root);
System.out.println();
System.out.println("后序遍历:");
tree.postRootTraverse(tree.root);
System.out.println();
System.out.println("叶子结点的个数为:"+tree.getLeafNode(tree.root));
System.out.println("二叉树的深度为:"+tree.getDepth(tree.root));
}
}