一个用于实现初始化指定个数的完全二叉树,以及两个非递归的深度优先遍历,和广度优先遍历
- package fifth;
- import java.util.Random;
- public class Tool{
- public static Random rand= new Random();
- }
- -------------------------------------------------------------
- package fifth;
- import java.util.EmptyStackException;
- import java.util.LinkedList;
- import java.util.Queue;
- import java.util.Stack;
- public class Tree {
- //用来实现非递归的广度优先查询与构造需要的队列
- public static Queue
que= new LinkedList (); - //用来实现深度优先查询需要的栈
- public static Stack
stack=new Stack (); - //存储的节点信息
- public int data;
- public Tree leftNode=null;
- public Tree rightNode=null;
- //用来实现遍历的临时节点
- public Tree cTree=null;
- public Tree() {
- data=Tool.rand.nextInt(200);
- display();
- }
- public void display(){
- System.out.print(data+",");
- }
- /**
- * 创建一个以这个节点为定点的完全二叉树
- * 这个中初始化方法类似于广度优先遍历
- * @param count 要创建的完全二叉树的节点个数
- */
- public void initTree(int count){
- que.add(this);
- while((cTree=que.poll())!=null)
- {
- //当树中需要创建节点数小于两个时,那么就应该创造完叶子节点然后返回
- //当树中需要创建节点个数大于两个时,那么就应该把创造的子节点放入队列中,等待创建它的子节点
- if(count-2>0)
- {
- cTree.leftNode=new Tree();
- que.add(cTree.leftNode);
- count--;
- cTree.rightNode=new Tree();
- que.add(cTree.rightNode);
- count--;
- }
- else if(count==0)
- {
- break;
- }
- else if(count==1)
- {
- cTree.leftNode=new Tree();
- count--;
- break;
- }
- else
- {
- cTree.leftNode=new Tree();
- cTree.rightNode=new Tree();
- count-=2;
- }
- }
- }
- /**
- * 非递归的广度优先遍历,用的队列来实现
- */
- public void breadthSearch(){
- System.out.print(' '+"非递归广度优先遍历:");
- //清空队列,同时把自己放在队列的第一个元素
- que.clear();que.add(this);
- while((cTree=que.poll())!=null)
- {
- //访问队列中的数据
- cTree.display();
- if(cTree.leftNode!=null)
- {
- que.add(cTree.leftNode);
- }
- if(cTree.rightNode!=null)
- {
- que.add(cTree.rightNode);
- }
- }
- }
- /**
- * 用于栈来实现的非递归深度优先遍历 前序遍历
- */
- public void deepFirstSearch(){
- System.out.print(' '+"非递归深度优先遍历,前序遍历:");
- //首先把自己压入栈底
- this.display();
- cTree=this;
- while(cTree!=null)
- {
- if(cTree.leftNode!=null)
- {
- stack.add(cTree);
- cTree.leftNode.display();
- cTree=cTree.leftNode;
- }
- else
- {
- while(cTree.rightNode==null)
- {
- try
- {
- cTree=stack.pop();
- }
- catch(EmptyStackException e)
- {
- return;
- }
- }
- cTree.rightNode.display();
- cTree=cTree.rightNode;
- }
- }
- }
- public static void main(String[] args) {
- Tree tree= new Tree();
- tree.initTree(10);
- System.out.println();
- tree.leftNode.display();
- tree.rightNode.display();
- tree.breadthSearch();
- tree.deepFirstSearch();
- }
- }