//后跟次序周游 非递归
//同一二叉树可能先后两次进栈
//设置标志
typedef struct{
int tag;
BinTree t;
}Elem;
void nPostOrder1(BinTree t)
{
Stack s;
Elem stnode;
BinTreeNode *p = t;
if(t == NULL) return ;
s = createEmptyStack();
do{
while(p!=NULL){
stnode.t = p;
stnode.tag = 1;
push(s,stnode);
p = leftChild(p); //左节点一直进栈
}
while(!isEmptyStack(s)){
stnode = top(s);
pop(s); //弹栈
p = stnode.t;
if(stnode.tag == 1) //是第一次进栈
{
stnode.tag = 2; //第二次进栈
push(s,stnode);
p = rightChild(p); //周游其右节点
break; //退出本次循环
}
else visit(root(p)); //周游其根节点
}
}while(!isEmptyStack(s));
}
修改
void nPostOrder2(BinTree t)
{
Stack s = createEmptyStack();
BinTree p = t;
while(p!=NULL || !isEmptyStack(s))
{
while(p!=NUL){
push(s,p);
p = leftChild(p)?leftChild(p):rightChild(p); //
}
p = top(s)
pop(s);
visit(root(p)); //栈顶为访问节点
if(!isEmptyStack(s) && leftChild(top(s)) == p){ //栈非空且从左子树退回
p = rightChild(top(s));
else p=NULL; //从右子树回来 推到上一层处理
}
}
}
广度优先周游
void levelOrder(BinTree t)
{
BinTree c,cc;
Queue q = createNullQueue();
if (t == NULL) {
/* code */
return ;
c=t;
enQueue(q,c); // 树根先入队
while(!isEmptyStack(q))
{
c = frontQueue(q); deQueue(q); visit(root(c)); //队首出队,并访问
c = leftChild(c); if(cc!=NULL) enQueue(q,cc); //将左子树送入队列
cc = rightChild(c); if(cc!=NULL) enQueue(q,cc); //右子树入队
}
}
}