利用栈的方法来遍历
先访问将根结点和左子树根结点压栈,然后不断访问左子树,直到NULL,再访问左子树下的右子树,遇到NULL,就出栈。大类的右子树和左子树差不多
思路如下图:
代码
#include <stdio.h>
#include <malloc.h>
typedef struct BiNode{//二叉树结点类型
char data;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
typedef struct{//栈存储类型
BiNode **base;//如果不是双指针的话,压栈的时候会显示错误: incompatible types when assigning to type 'BiNode' from type 'BiTree'|,差距就在一个指针
BiNode **top;
int stack_size;
}SqStack;
////先序创建
BiTree BiTree_Creat(BiTree T)
{
char ch;
scanf("%c",&ch);
if('#'==ch)
T=NULL;
else{
T=(BiTree)malloc(sizeof(BiNode));
T->data=ch;
T->lchild=BiTree_Creat(T->lchild);
T->rchild=BiTree_Creat(T->rchild);
}
return T;
}
SqStack *InitStack(SqStack *S)
{
if (!(S = (SqStack *)malloc(sizeof(SqStack))))exit(-1);
S->base=(BiNode **)malloc(100*sizeof(BiNode*));
if(!S->base)
printf("error");
S->top=S->base;
S->stack_size=100;
return S;
}
void Push(SqStack *S,BiTree T)
{
if(S->top-S->base>=S->stack_size)
{
S->base=(BiNode **)realloc(S->base,(S->stack_size+10)*sizeof(BiNode*));
if(!S->base)
printf("error");
S->top=S->base+S->stack_size;
S->stack_size+=10;
}
*(S->top)=T;
S->top++;
}
BiNode** Pop(SqStack *S)
{
BiNode** e;
if(S->top==S->base)
printf("Pop error");
S->top--;
e=*S->top;
return e;
}
int StackEmpty(SqStack *S)
{
if(S->top==S->base)
return 1;
else{
return 0;
}
}
void InOrderTraverse(BiTree T,SqStack *S)
{
BiTree p;
S=InitStack(S);
p=T;
while(p||!StackEmpty(S))
{
if(p)
{
Push(S,p);
p=p->lchild;
}
else{
p=Pop(S);
printf("%c",p->data);
p=p->rchild;
}
}
}
int main()
{
BiTree T;
SqStack *S;
S=InitStack(S);
T=BiTree_Creat(T);
printf("中序非递归遍历:\n");
InOrderTraverse(T,S);
return 0;
}
本文介绍了一种使用栈实现二叉树中序遍历的算法。通过将根节点及左子树节点压栈,随后不断访问左子树直至空节点,再访问右子树并遇到空节点则出栈,以此完成遍历过程。

被折叠的 条评论
为什么被折叠?



