您的位置:首页 > 编程语言 > Java开发

完全二叉树的JAVA实现(以及非递归遍历方法)

2011-10-09 20:47 771 查看
一个用于实现初始化指定个数的完全二叉树,以及两个非递归的深度优先遍历,和广度优先遍历

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<Tree> que= new LinkedList<Tree>();
//用来实现深度优先查询需要的栈
public static Stack<Tree> stack=new Stack<Tree>();
//存储的节点信息
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('\n'+"非递归广度优先遍历:");
//清空队列,同时把自己放在队列的第一个元素
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('\n'+"非递归深度优先遍历,前序遍历:");
//首先把自己压入栈底
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();
}
}


本文出自 “老江北” 博客,转载请与作者联系!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: