import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
//孩子链表表示法
public class CTree<AnyType>{
PLNode nodes[]=new PLNode[20];
int n;
PLNode rootNode;
class CNode<AnyType>{
int child;
CNode nextChild;
public CNode(int child){
this.child=child;
this.nextChild=null;
}
}
class PLNode<AnyType>{
char data;
CNode firstChild;
public PLNode(char data){
this.data=data;
this.firstChild=null;
}
}
public CTree(){
n=0;
}
public void creatTree(){
Queue<PLNode> q=new LinkedList<PLNode>();
Scanner sc=new Scanner(System.in);
System.out.println("请输入根节点");
String a=sc.next();
char b[]=a.toCharArray();
rootNode=new PLNode(b[0]);
nodes[0]=rootNode;
n++;
q.add(rootNode);
while(!q.isEmpty()&&n<nodes.length){
PLNode p=q.remove();
System.out.println("请输入"+p.data+"的所有孩子,没有则输入# :");
String c=sc.next();
char d[]=c.toCharArray();
if(d[0]!='#'){
PLNode newNode=new PLNode(d[0]);
nodes[n]=newNode;
q.add(newNode);
p.firstChild=new CNode(n);
CNode child=p.firstChild;
n++;
for(int i=1;i<d.length;i++){ //有两个以上的孩子走这一步
PLNode newNode2=new PLNode(d[i]);
nodes[n]=newNode2;
q.add(newNode2);
child.nextChild=new CNode(n);
child=child.nextChild;
n++;
}
child.nextChild=null;
if(n>nodes.length){
increaseSpace(nodes.length+15);
}
}
else
p.firstChild=null;
}
}
public void increaseSpace(int newSpace){ //扩容
int size=nodes.length;
PLNode b[]=nodes;
nodes=new PLNode[newSpace];
for(int i=0;i<size;i++){
nodes[i]=b[i];
}
}
//层次非递归遍历
public void levelQueueOrder(){
Queue<Integer> q=new LinkedList<Integer>();
q.add(0); //根结点入队
System.out.println(nodes[0].data);
while(!q.isEmpty()){
int step=q.remove();
CNode p=nodes[step].firstChild;
while(p!=null){
System.out.println(nodes[p.child].data);
q.add(p.child);
p=p.nextChild;
}
}
}
public static void main(String[] args) {
CTree<String> ct=new CTree<String>();
ct.creatTree();
System.out.println("层次遍历");
ct.levelQueueOrder();
}
}