/*
这是一个二叉树的练习,
data:2013/10/18 7:37
练习一下二叉树的中序,前序,后续。。遍历
*/
class Tree1{
public static void main(String args[]){
// 叶子节点
TreeModels t15=new TreeModels(null,null,15);
TreeModels t14=new TreeModels(null,null,14);
TreeModels t13=new TreeModels(null,null,13);
TreeModels t12=new TreeModels(null,null,12);
TreeModels t11=new TreeModels(null,null,11);
TreeModels t10=new TreeModels(null,null,10);
TreeModels t9=new TreeModels(null,null,9);
TreeModels t8=new TreeModels(null,null,8);
//内部节点
TreeModels t7=new TreeModels(t14,t15,7);
TreeModels t6=new TreeModels(t12,t13,6);
TreeModels t5=new TreeModels(t10,t11,5);
TreeModels t4=new TreeModels(t8,t9,4);
TreeModels t3=new TreeModels(t6,t7,3);
TreeModels t2=new TreeModels(t4,t5,2);
//根节点
TreeModels t1=new TreeModels(t2,t3,1);
preGet1(t1);//先序
orGet1(t1);//中序
}
public static void preGet1(TreeModels root){//先序(非递归),利用栈
TreeStack ts=new TreeStack();//定义一个栈
while(root!=null||ts.index!=0){
while(root!=null){
System.out.print(root.getData()+" ");
ts.push(root); //将经过的根节点压入栈
root=root.getLeft();//读取左孩子节点
}
root=ts.pop(); //将根节点 退栈
root=root.getRight();//遍历根节点右孩子节点
if(root==null)
//这种情况是 当遍历到最左下节点时,该节点的右孩子为空,但是栈内还存在没有遍历完的根节点,所以continue;
continue;
}
}
public static void orGet1(TreeModels root){//中序(非递归),利用栈
TreeStack ts=new TreeStack();
TreeModels root1=null; //root用来存放已经遍历过得 根节点
while(root!=null||ts.index!=0){
while(root!=null&&root!=root1){//遍历过的根节点,不再遍历它的左节点
ts.push(root);
root=root.getLeft();
}
//当栈内还有节点时,每次执行一次,作为上面while循环的 根节点去遍历它的左子树
root=ts.pop();
System.out.print(root.getData()+" ");
root1=root;
root=root.getRight();
}
}
public static void LaGet(TreeModels root){//后续(递归遍历)
if(root!=null){
LaGet(root.getLeft());
LaGet(root.getRight());
System.out.print(root.getData()+" ");
}
}
class TreeModels{//建立一个树模型
private TreeModels left;
private TreeModels right;
private int data;
public TreeModels(TreeModels left,TreeModels right,int data){
this.left=left;
this.right=right;
this.data=data;
}
public void setLeft(TreeModels left){
this.left=left;
}
public void setRight(TreeModels right){
this.right=right;
}
public void setLeft(int data){
this.data=data;
}
public TreeModels getLeft(){
return left;
}
public TreeModels getRight(){
return right;
}
public int getData(){
return data;
}
}
class TreeStack{//存放数据的栈,底层基于数组
int index=0;;
TreeModels tms[]=new TreeModels[15];//存放的树节点只有四层。。
public void push(TreeModels tm){
if(index>tms.length){
System.out.println("栈溢出。。。");
return ;
}
index++;
tms[index]=tm;
}
public TreeModels pop(){
TreeModels ts=null;
if(index==0){
System.out.println("栈内数据已取完、、、");
return ts;
}
ts=tms[index];
index--;
return ts;
}
}
后续算法的 非递归由于个人能力原因,写不下去呵呵。。
后序遍历思路:
1.先遍历左子树将其压入栈,
2.将栈中的节点作为根节点,判断是否为空或者受到过遍历受到过遍历(有一个变量进行记录),如果是,则输入该节点,否则执行3.
3.遍历右子树
欢迎大家 贴出后序遍历的 代码。。我学习学习
下面为运行结果(有的我注释了。。):