二叉树的中序非递归遍历
中序遍历的非递归算法描述如下:
- 从根节点开始检索,如果当前节点不为空,则将当前节点入栈,让当前节点成为其左孩子节点,再继续上一步的操作
- 加入当前节点为空了,说明其父节点已经没有左孩子了,那么将栈顶元素出栈并输入
- 判断栈顶元素是否有右孩子,如果有右孩子,则停止依次继续出栈的操作,并检索它的右孩子,重复第一步;如果没有右孩子,则继续将栈顶元素出栈
- 当栈为空,并且当前节点为空时,遍历完成,退出;
#include<stdio.h>
#include<stdlib.h>
typedef struct BTreeNode
{
int data;
struct BTreeNode *left;
struct BTreeNode *right;
}BTreeNode,*BTree;
typedef struct stack
{
BTree * data;
int top;
int size;
}stack;
InitStack(stack *s)
{
s->top=0;
s->size=0;
s->data=(BTree *)malloc(sizeof(BTree));
}
Push(stack *s,BTree t)
{
s->size++;
realloc(s->data,sizeof(BTree)*(s->size));
s->data[s->top++]=t;
}
BTree Pop(stack *s)
{
if(s->size<=0)
{
printf("the stack is empty!\n");
return NULL;
}
s->size--;
return s->data[--s->top];
}
BTree BuildTree()
{
int data;
BTree root=NULL;
scanf("%d",&data);
if(data!=-1)
{
root=(BTree)malloc(sizeof(BTreeNode));
root->data=data;
root->left=BuildTree();
root->right=BuildTree();
}
return root;
}
void InOrder(BTree root)//中序递归遍历
{
if(root!=NULL)
{
InOrder(root->left);
printf("%d ",root->data);
InOrder(root->right);
}
}
void InOrder_NoRecursion (BTree root)//中序非递归遍历
{
BTree t=root;
stack s;
InitStack(&s);//初始化栈
while(t!=NULL||s.size!=0)
{
while(t!=NULL)
{
Push(&s,t);
t=t->left;
}
while(s.size!=0)
{
t=Pop(&s);
printf("%d ",t->data);
t=t->right;
if(t!=NULL) break;
}
}
}
main()
{
printf("请以先序方式创建二叉树:\n");
BTree root=BuildTree();
printf("中序递归遍历二叉树的结果为:\n");
InOrder(root);
printf("\n中序非递归遍历二叉树的结果为:\n");
InOrder_NoRecursion(root);
}