版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/benzhaohao/article/details/78501393
//由先根和中根遍历建立二叉树
public class bitree{
public bitree(String preorder,String inorder,int preindex,int inindex,int count){
if(count>0){ //先根中根为空
char r=preorder.charAt(preindex); //取先根遍历中的第一个结点作为根节点
int i=0;
for(;i<count;i++) //寻找根节点在中根遍历序列中的位置
if(r==inorder.charAt(i+inindex))
break;
root=new bitreeNode(r); //建立树的根节点
root.setlchild(new bitree(preorder,inorder,preindex+1,inindex,i).root); //建立树的左子树
root.setrchild(new bitree(preorder,inorder,preindex+1+i,inindex+1+i,count-i-1).root); //建立树的右子树
}
}
//由标明空子树先根遍历序列建立一颗二叉树,并返回其根节点
private static int index=0; //用于记录prestr的索引值
public bitree(String prestr){
char c=prestr.charAt(index++);
//取出字符串索引为index的字符且index增1
if(c!='#'){ //字符串不为空
root=new bitreeNode(c); //建立树的根节点
root.setlchild(new bitree(prestr).root); //建立树的左子树
root.setrchild(new bitree(prestr).root); //建立树的右子树
}
else
root=null;
}
//根据完全二叉树顺序存储结构建立二叉树链式存储结构
public bitreeNode createbitree(String sqbitree,int index){
bitreeNode root=null; //根节点初始化为空
if(index<sqbitree.length()){
root=new bitreeNode(sqbitree.charAt(index)); //建立树的根节点
root.setlchild(createbitree(sqbitree,2*index+1)); //建立树的左子树
root.setrchild(createbitree(sqbitree,2*index+2)); //建立树的右子树
}
return root;
}
}
在写测试用例时,遇到的问题
1、调用类。
如果另一个类中的那个方法是私有的话,就不能直接调用到,如果是其他类型的话看情况,如果是静态的(static)话,直接用类名可以调用到,如果是非静态的,就需要利用另一个类的实例(也就是用那个类生成的对象)来调用。
class A{
public static void a(){}
public void b(){}
}
public class B{
public static void main(String[] args){
A.a();//静态
new A().b();//非静态
}
}
2、由标明空子树先根遍历序列时,index前必须加static,否则会陷入死循环,因为如不加static,index会一直从0开始执行
3、遍历实现的代码在前面文章已经实现
public class example {
public static void main(String[] args){
//由先根遍历和中根遍历遍历二叉树
String preorder="abdegcfh";
String inorder="dbgeafhc";
bitree t1=new bitree(preorder,inorder,0,0,preorder.length());
bitreeNode root=t1.root;
System.out.println("后根遍历");
t1.postroottraverse(root);
//由标明空子树先根遍历序列建立二叉树
String prestr="ab##cd###";
bitree t2=new bitree(prestr);
bitreeNode root2=t2.root;
System.out.println();
System.out.println("先根遍历");
t2.preroottraverse(root2);
System.out.println();
System.out.println("中根遍历");
t2.inroottraverse(root2);
//由完全二叉树顺序存储结构建立二叉链式存储结构
String sqbitree="abcdefgh";
bitree w=new bitree();
bitreeNode root3=w.createbitree(sqbitree,0);
System.out.println();
System.out.println("先根遍历");
bitree t3=new bitree(root);
t3.preroottraverse(root3);
}