java由先根中根遍歷序列建立二叉樹,由標明空子樹建立二叉樹,有完全二叉樹順序儲存結構建立二叉鏈式儲存結構
阿新 • • 發佈:2018-12-01
//由先根和中根遍歷建立二叉樹 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); }