树的孩子链表表示法可执行代码(创建,层次遍历)
2013-12-31 20:46
363 查看
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 =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 =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(); } }
相关文章推荐
- 树的孩子链表表示法可执行代码(创建,层次遍历)
- 树的孩子链表表示法可执行代码(创建,层次遍历)
- 树的双亲表示法可执行代码(创建树,层次遍历,求深度)
- 树的双亲表示法可执行代码(创建树,层次遍历,求深度)
- 树的双亲表示法可执行代码(创建树,层次遍历,求深度)
- 哈夫曼树可执行代码(创建,层次遍历)
- 哈夫曼树可执行代码(创建,层次遍历)
- 哈夫曼树可执行代码(创建,层次遍历)
- 初学链表之链表的创建与遍历
- 数据结构之静态链表的游标表示及其实现(附完整代码)
- (C语言版)链表(一)——实现单向链表创建、插入、删除等简单操作(包含个人理解说明及注释,新手跟着写代码)
- 二叉树的创建、二叉排序树、前序、中序、后序、层次遍历
- 简单链表的创建与遍历
- 采用二叉链表结构实现二叉树,并以递归遍历思想实现二叉树的创建、二叉树的遍历(先序、中序、后序和层次遍历)
- 树、森林与二叉树(树的存储结构(树的孩子兄弟链表应用举例),树转换为二叉树,二叉树转换成树和森林,树和森林的遍历)
- 二叉树的先序创建,先序,中序,后序的递归与非递归遍历,层次遍历,叶子结点数及树的深度
- 二叉树的创建、层次遍历、递归及非递归先中后序遍历
- 链表的创建和遍历
- C++层次遍历创建完全二叉树及四种遍历输出
- 数据结构算法代码实现——线性表的链式表示与实现(单链表)(三 )