package TreeNodePack;
import java.util.Stack;
public class BinTree {
private char date;
private BinTree lchild;
private BinTree rchild;
public BinTree(char c){
date=c;
}
//先序遍历,递归
public static void preOrder(BinTree t){
if(t==null){
return;
}
System.out.print(t.date);
preOrder(t.lchild);
preOrder(t.rchild);
}
//中序遍历递归
public static void InOrder(BinTree t){
if(t==null){
return;
}
InOrder(t.lchild);
System.out.println(t.date);
InOrder(t.rchild);
}
//后续遍历递归
public static void PostOrder(BinTree t){
if(t==null){
return;
}
PostOrder(t.lchild);
PostOrder(t.rchild);
System.out.println(t.date);
}
//先序遍历非递归
public static void PreOrder2(BinTree t){
Stack<BinTree>s=new Stack<BinTree>();
while(t!=null||!s.empty()){
while(t!=null){
System.out.println(t.date);
s.push(t);//使用Stack存储t是为了找到节点的右子树
t=t.lchild;
}
if(!s.empty()){
t=s.pop();
t=t.rchild;
}
}
}
//中序遍历非递归
public static void InOrder2(BinTree t){
Stack<BinTree>s=new Stack<BinTree>();
while(t!=null||!s.isEmpty()){
while(t!=null){
s.push(t);
t=t.lchild;
}
if(!s.isEmpty()){
t=s.pop();
System.out.println(t.date);
t=t.rchild;
}
}
}
//后续遍历非递归
public static void PostOrder2(BinTree t){
Stack<BinTree>s=new Stack<BinTree>();
Stack<Integer>flag=new Stack<Integer>();
Integer i=new Integer(1);//设置一个右子树访问标志位,表示节点t的右子树是否访问,1表示访问过,0表示没有访问过
while(t!=null||!s.isEmpty()){
while(t!=null){//对于节点t,当节点t不为空时,把节点t入栈s,同时其右子树的访问标志位为0,将其入栈flag
s.push(t);
flag.push(new Integer(0));
t=t.lchild;
}
while(!s.isEmpty()&&flag.peek().equals(i)){//假如一个节点的右子树访问标志位等于1,表示该节点的右子树已经访问过
flag.pop();//把flag栈中的该节点的标志位取出
System.out.println(s.pop().date);//打印该节点
}
if(!s.empty()){//假如一个节点的右子树访问标志位等于0表示该节点的右子树没有访问过
flag.pop();//将原来的0取出
flag.push(new Integer(i));//放入1
t=s.peek();//取s栈顶的元素,但是不改变栈s,注意不能用pop(),因为此时该节点还没有输出
t=t.rchild;
}
}
}
public static void main(String[] args) {
BinTree b1=new BinTree('a');
BinTree b2=new BinTree('b');
BinTree b3=new BinTree('c');
BinTree b4=new BinTree('d');
BinTree b5=new BinTree('e');
b1.lchild=b2;
b1.rchild=b3;
b2.lchild=b4;
b2.rchild=b5;
System.out.println("前序遍历");
BinTree.PreOrder2(b1);
System.out.println("中序遍历");
BinTree.InOrder2(b1);
System.out.println("后序遍历");
BinTree.PostOrder2(b1);
}
}
二叉树的遍历(递归与非递归)
最新推荐文章于 2024-04-08 22:10:05 发布