二叉树的非递归中序遍历
基本思想:从根结点一直向左走,走的过程入栈,直到左子树为空则访问;
然后退栈,查看是否有右指针,若有则以其为根再找最左下结点,否则访问
结合上篇二叉链表
BiTNode *GoFarLeft(BiTree* T,SqStack *S)
{
if (!T)
{
return NULL;
}
while(T->lchild)
{
Push(S,*T);
T=T->lchild;
}
return T;
}
/**二叉树的非递归中序遍历*/
void InOrder(BiTree *T)
{
SqStack *S=(SqStack *)malloc(sizeof(SqStack));
initStack(S);
BiTNode *t=GoFarLeft(T,S);
while(t)
{
printf("%d ",t->data);//访问最左下结点
if (t->rchild)
{
t=GoFarLeft(t->rchild,S);
}
else if (!IsStackEmpty(*S))
{
t=Pop(S);
}
else
{
t=NULL;//栈空结束
}
}
}
用到栈的操作代码
/************************************************************************/
/* 栈的顺序存储结构 */
/************************************************************************/
#define stack_init_size 100
#define stackincrement 10
typedef BiTNode SElemType;
typedef struct StackName
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
/*栈的初始化*/
bool initStack(SqStack *S)
{
//构造一个空栈
S->base=(SElemType*)malloc(stack_init_size*sizeof(SElemType));
if (!S->base)
{
return false;
}
S->top=S->base;
S->stacksize=stack_init_size;
return true;
}
/*入栈*/
bool Push(SqStack *S,SElemType e)
{
//printf("%d 入栈完成!\n",e);
if (S->top-S->base>=S->stacksize)//栈满
{
S->base=(SElemType*)realloc(S->base,(S->stacksize+stackincrement)*sizeof(SElemType));
if (!S->base)
{
return false;
}
S->stacksize=S->stacksize+stackincrement;
}
*S->top++=e;
return true;
}
/*出栈*/
SElemType* Pop(SqStack *S)
{
if (S->top==S->base)//栈空
{
return NULL;
}
return --S->top;
}
/*判断栈是否为空*/
bool IsStackEmpty(SqStack S)
{
if (S.top==S.base)
{
return true;
}
else
{
return false;
}
}