http://blog.csdn.net/pipisorry/article/details/37353037
c實現
1.先序遍歷非遞歸算法
#define maxsize 100
typedef struct {
Bitree Elem[maxsize];
int top;
} SqStack;
void PreOrderUnrec(Bitree t) {
SqStack s;
StackInit(s);
p=t;
while (p!=null || !StackEmpty(s)) {
while (p!=null) { //遍歷左子樹
visite(p->data);
push(s,p);
p=p->lchild;
}//endwhile
if (!StackEmpty(s)) { //經過下一次循環中的內嵌while實現右子樹遍歷
p=pop(s);
p=p->rchild;
}//endif
}//endwhile
}//PreOrderUnrec
2.中序遍歷非遞歸算法
#define maxsize 100
typedef struct {
Bitree Elem[maxsize];
int top;
} SqStack;
void InOrderUnrec(Bitree t) {
SqStack s;
StackInit(s);
p=t;
while (p!=null || !StackEmpty(s)) {
while (p!=null) { //遍歷左子樹
push(s,p);
p=p->lchild;
}//endwhile
if (!StackEmpty(s)) {
p=pop(s);
visite(p->data); //訪問根結點
p=p->rchild; //經過下一次循環實現右子樹遍歷
}//endif
}//endwhile
}//InOrderUnrec
3.後序遍歷非遞歸算法
#define maxsize 100
typedef enum {L,R} tagtype;
typedef struct {
Bitree ptr;
tagtype tag;
} stacknode;
typedef struct {
stacknode Elem[maxsize];
int top;
} SqStack;
void PostOrderUnrec(Bitree t) {
SqStack s;
stacknode x;
StackInit(s);
p=t;
do {
while (p!=null) { //遍歷左子樹
x.ptr = p;
x.tag = L; //標記爲左子樹
push(s,x);
p=p->lchild;
}
while (!StackEmpty(s) && s.Elem[s.top].tag==R) {
x = pop(s);
p = x.ptr;
visite(p->data); //tag爲R,表示右子樹訪問完畢,故訪問根結點
}
if (!StackEmpty(s)) {
s.Elem[s.top].tag =R; //遍歷右子樹
p=s.Elem[s.top].ptr->rchild;
}
} while (!StackEmpty(s));
}//PostOrderUnrec
#define maxsize 100
typedef struct {
Bitree Elem[maxsize];
int top;
} SqStack;
void PreOrderUnrec(Bitree t) {
SqStack s;
StackInit(s);
p=t;
while (p!=null || !StackEmpty(s)) {
while (p!=null) { //遍歷左子樹
visite(p->data);
push(s,p);
p=p->lchild;
}//endwhile
if (!StackEmpty(s)) { //經過下一次循環中的內嵌while實現右子樹遍歷
p=pop(s);
p=p->rchild;
}//endif
}//endwhile
}//PreOrderUnrec
2.中序遍歷非遞歸算法
#define maxsize 100
typedef struct {
Bitree Elem[maxsize];
int top;
} SqStack;
void InOrderUnrec(Bitree t) {
SqStack s;
StackInit(s);
p=t;
while (p!=null || !StackEmpty(s)) {
while (p!=null) { //遍歷左子樹
push(s,p);
p=p->lchild;
}//endwhile
if (!StackEmpty(s)) {
p=pop(s);
visite(p->data); //訪問根結點
p=p->rchild; //經過下一次循環實現右子樹遍歷
}//endif
}//endwhile
}//InOrderUnrec
3.後序遍歷非遞歸算法
#define maxsize 100
typedef enum {L,R} tagtype;
typedef struct {
Bitree ptr;
tagtype tag;
} stacknode;
typedef struct {
stacknode Elem[maxsize];
int top;
} SqStack;
void PostOrderUnrec(Bitree t) {
SqStack s;
stacknode x;
StackInit(s);
p=t;
do {
while (p!=null) { //遍歷左子樹
x.ptr = p;
x.tag = L; //標記爲左子樹
push(s,x);
p=p->lchild;
}
while (!StackEmpty(s) && s.Elem[s.top].tag==R) {
x = pop(s);
p = x.ptr;
visite(p->data); //tag爲R,表示右子樹訪問完畢,故訪問根結點
}
if (!StackEmpty(s)) {
s.Elem[s.top].tag =R; //遍歷右子樹
p=s.Elem[s.top].ptr->rchild;
}
} while (!StackEmpty(s));
}//PostOrderUnrec
c++實現:
ref:http://siwei1987.blog.51cto.com/430256/118551
from:http://blog.csdn.net/pipisorry/article/details/37353037