1. 程式人生 > >java建立樹及實現遍歷

java建立樹及實現遍歷

樹的儲存結構有四種

1、雙親連結串列儲存結構(查詢指定結點的雙親結點容易,但查詢指定結點的孩子結點不容易)

2、孩子連結串列儲存結構

3、雙親孩子連結串列儲存結構

4、孩子兄弟連結串列儲存結構

其中孩子兄弟連結串列儲存結構中結點類的描述

package practice4;

public class cstreeNode {
	private Object data; //結點的資料域
	private cstreeNode firstchild,nextsibling;  //左孩子,右兄弟
	public cstreeNode(){   //構造一個空結點
		this(null);
	}
	public cstreeNode(Object data){   //構造一個左孩子,右兄弟為空的結點
		this(data,null,null);
	}
	public cstreeNode(Object data,cstreeNode firstchild,cstreeNode nextsibling){
		this.data=data;
		this.firstchild=firstchild;
		this.nextsibling=nextsibling;
	}
	public Object getdata(){
		return data;
	}
	public cstreeNode getfirstchild(){
		return firstchild;
	}
	public cstreeNode getnextsibling(){
		return nextsibling;
	}
	public void setdata(Object data){
		this.data=data;
	}
	public void setfirstchild(cstreeNode firstchild){
		this.firstchild=firstchild;
	}
	public void setnextsibling(cstreeNode nextsibling){
		this.nextsibling=nextsibling;
	}
}

其中樹的遍歷中,層次遍歷需要用到佇列類,在前面文章已經實現

下面是遍歷的樹


package practice4;

public class cstree {
	private cstreeNode root;  //樹的根節點
	public cstree(){      //構造一棵空樹
		this.root=root;
	}
	public cstree(cstreeNode root){   //構造一棵樹
		this.root=root;
	}
	public void preroottraverse(cstreeNode t){  //樹的先根遍歷
		if(t!=null){
			System.out.print(t.getdata());
			preroottraverse(t.getfirstchild());
			preroottraverse(t.getnextsibling());
		}
	}
	public void postroottraverse(cstreeNode t){  //樹的後根遍歷
		if(t!=null){
			postroottraverse(t.getfirstchild());
			System.out.print(t.getdata());
			postroottraverse(t.getnextsibling());
		}
	}
	public void leveltraverse(cstreeNode t){   //樹的層次遍歷
		if(t!=null){
			Linkqueue l=new Linkqueue();
			l.offer(t);
			while(!l.isEmpty()){
				for(t=(cstreeNode)t.poll();t!=null;t=t.getnextsibling())
					System.out.print(t.getdata()+" ");
				if(t.getfirstchild()!=null)
					l.offer(t.getfirstchild());
			}
		}
	}
	public cstree createcstree(){   //建立樹
		cstreeNode k=new cstreeNode('k',null,null);
		cstreeNode f=new cstreeNode('f',k,null);
		cstreeNode e=new cstreeNode('e',null,f);
		cstreeNode g=new cstreeNode('g',null,null);
		cstreeNode l=new cstreeNode('l',null,null);
		cstreeNode j=new cstreeNode('j',null,null);
		cstreeNode i=new cstreeNode('i',l,j);
		cstreeNode h=new cstreeNode('h',null,i);
		cstreeNode d=new cstreeNode('d',h,null);
		cstreeNode c=new cstreeNode('c',g,d);
		cstreeNode b=new cstreeNode('b',e,c);
		cstreeNode a=new cstreeNode('a',b,null);
		return new cstree(a);   //建立根節點為a的樹
	}
	public static void main(String[] args){
		cstree debug=new cstree();  
		cstree cs=debug.createcstree();
		cstreeNode root=cs.root;  //取得樹的根節點
		System.out.println("樹的先根遍歷");
		cs.preroottraverse(root);
		System.out.println();
		System.out.println("樹的後根遍歷");
		cs.postroottraverse(root);
	}
}

執行結果