数据结构之二叉树遍历,非递归算法(Java实现)
栈存储结构
public class Sqstack {
public String data;
public TowTree next;
public Sqstack(){
this.data=null;
this.next=null;
}
public boolean EmpatyStack(Sqstack S){
if(S.next==null){
return true;
}
return false;
}
}
public class TowTree {
String data;
TowTree lift;
TowTree right;
TowTree next;
TowTree(){
this.data=null;
this.lift=this.right=null;
this.next=null;
}
public static void main(String[] args) {
TowTree T = new TowTree();
CreateBiTree(T);
System.out.println("先序遍历");
PreOrder(T);
System.out.println();
System.out.println("中序遍历");
InOrder(T);
System.out.println();
System.out.println("后序遍历");
PostOrder(T);
}
public static void CreateBiTree(TowTree T){
Scanner sc= new Scanner(System.in);
System.out.println("输入:");
String x=sc.next();
if(x.equals("0")){
T=null;
}
if(T!=null){
T.data=x;
TowTree Tl=new TowTree();
T.lift=Tl;
TowTree Tr=new TowTree();
T.right=Tr;
CreateBiTree(T.lift);
CreateBiTree(T.right);
}
}
public static void InOrder(TowTree T){
Sqstack S = new Sqstack();
while (T!=null || !S.EmpatyStack(S)){
if(T!=null){
T.next=S.next;
S.next=T;
T=T.lift;
}else {
if( S.next.data!=null){
System.out.print(S.next.data);
}
T=S.next.right;
S.next=S.next.next;
}
}
}
public static void PreOrder(TowTree T){
Sqstack S = new Sqstack();
while (T!=null || !S.EmpatyStack(S)){
if(T!=null){
if (T.data!=null){
System.out.print(T.data);
}
T.next=S.next;
S.next=T;
T=T.lift;
}else {
T=S.next.right;
S.next=S.next.next;
}
}
}
public static void PostOrder(TowTree T1){
Sqstack S = new Sqstack();
TowTree T = new TowTree();
TowTree t = new TowTree();
T=T1;
while (T!=null || !S.EmpatyStack(S)){
if(T!=null){
T.next=S.next;
S.next=T;
T=T.lift;
}else {
T=S.next;
if(T.right!=null && T.right!=t){
T=T.right;
}else {
T=null;
if(S.next.data!=null){
System.out.print(S.next.data);
}
t=S.next;
S.next=S.next.next;
}
}
}
}
}
|