

typedef struct TreeNode *BinTree;typedef BinTree Position; struct TreeNode{ElementType Data;BinTree Left;BinTree Right; }; BinTree BT;
void InOrderTraversal(BinTree BT)//中序遍歷非遞歸遍歷算法(使用堆棧,用循環實現){BinTree T=BT;Stack S=CreakStack(MaxSize);//創建并初始化堆棧Swhile(T||!IsEmpty(S)){while(T){//一直向左并將沿途結點壓入堆棧Push(S,T);T=T->Left; }if(!IsEmpty(S)){T=Pop(S);//結點彈出堆棧PRintf("%5d",T->Data);//(訪問)打印結點T=T->Right;//轉向右子樹 } } }void PreOrderTraversal(BinTree BT)//先序遍歷非遞歸遍歷算法(使用堆棧,用循環實現){BinTree T=BT;Stack S=CreakStack(MaxSize);//創建并初始化堆棧Swhile(T||!IsEmpty(S)){while(T){//一直向左并將沿途結點壓入堆棧printf("%5d",T->Data);//(訪問)打印結點Push(S,T);T=T->Left; }if(!IsEmpty(S)){T=Pop(S);//結點彈出堆棧T=T->Right;//轉向右子樹 } } } void PostOrderTraversal( BinTree BT )//后序遍歷非遞歸遍歷算法(使用堆棧,用循環實現) { BinTree T BT; Stack S = CreatStack( MaxSize ); /*創建并初始化堆棧S*/ Stack Q = CreatStack( MaxSize ); /*創建并初始化堆棧Q,用于輸出反向*/ while( T || !IsEmpty(S) ){ while(T){ /*一直向右并將沿途結點壓入堆棧*/ Push(S,T); Push(Q,T);/*將遍歷到的結點壓棧,用于反向*/ T = T->Right; } if(!IsEmpty(S)){ T = Pop(S); /*結點彈出堆棧*/ T = T->Left; /*轉向左子樹*/ } } while( !IsEmpty(Q) ){ T = Pop(Q); printf(“%5d”, T->Data); /*(訪問)打印結點*/ } }
新聞熱點
疑難解答