树的存储结构有四种
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);
}
}
运行结果