二叉樹三種遍歷非遞迴演算法
阿新 • • 發佈:2019-02-17
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