先序遍历:
void PreOrderUnrec(Bitree *t) { Stack s; StackInit(s); Bitree *p=t; while (p!=NULL || !StackEmpty(s)) { while (p!=NULL) //遍历左子树 { visite(p->data); push(s,p); p=p->lchild; } if (!StackEmpty(s)) //通过下一次循环中的内嵌while实现右子树遍历 { p=pop(s); p=p->rchild; }//endif }//endwhile }
中序遍历
void InOrderUnrec(Bitree *t) { Stack s; StackInit(s); Bitree *p=t; while (p!=NULL || !StackEmpty(s)) { while (p!=NULL) //遍历左子树 { push(s,p); p=p->lchild; } if (!StackEmpty(s)) { p=pop(s); visite(p->data); //访问根结点 p=p->rchild; //通过下一次循环实现右子树遍历 }//endif }//endwhile }
判断二叉排序树:
void InOrderUnrec(Bitree *t) { Stack s; StackInit(s); Bitree *p=t; Bitree t[100],i=0,j; while (p!=NULL || !StackEmpty(s)){ while (p!=NULL) //遍历左子树{ push(s,p); p=p->lchild; } if (!StackEmpty(s)){ p=pop(s); // visite(p->data); //访问根结点 t[++i]=p; p=p->rchild; //通过下一次循环实现右子树遍历 }//endif }//endwhile for(j=0; j<i-1; j++){ if(t[i]>=t[i+1]){ printf("不是二叉排序树\n"); return ; } } printf("是二叉排序树\n"); }
后序遍历
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