非递归方法利用一个堆栈来将处理。
代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
char data;
struct Node *lchild,*rchild;
}*BitTree,Node;
typedef struct Stack
{
Node *key[20];
int top;
}stack;
void initialize(stack *stack1)
{
stack1->top=0;
}
void push(stack *stack1,Node *key)
{
stack1->key[++stack1->top]=key;
}
bool IsEmpty(stack *stack1)
{
if(stack1->top==0)
return true;
else
return false;
}
Node * pop(stack *stack1)
{
Node *temp=stack1->key[stack1->top];
stack1->top--;
return temp;
}
//非递归先序遍历
void PreorderTraverse1(BitTree root)
{
BitTree root1=root;
stack *s=(stack*)malloc(sizeof(stack));
initialize(s);
//根结点入栈
if(root1)
push(s,root1);
while(!IsEmpty(s))
{
root1=pop(s);//栈顶结点出栈
printf("%c->",root1->data);
if(root1->rchild!=NULL)//左孩子结点入栈
push(s,root1->rchild);
if(root1->lchild!=NULL)//右孩子结点入栈
push(s,root1->lchild);
}
}
非递归中序遍历
void InorderTraverse1(BitTree root)
{
BitTree root1=root;
stack *s=(stack*)malloc(sizeof(stack));
initialize(s);
while(root1||!IsEmpty(s))
{
//压栈直到左子树为空
while(root1)
{
push(s,root1);
root1=root1->lchild;
}
if(!IsEmpty(s))
{
root1=pop(s);//出栈
printf("%c->",root1->data);
root1=root1->rchild;//指向该结点的右孩子回到while循环
}
}
}
//非递归后序遍历(这个比较难理解)
void PostorderTraverse1(BitTree root)
{
BitTree root1=root;
Node *temp=(Node*)malloc(sizeof(Node));
stack *s=(stack*)malloc(sizeof(stack));
int tag[20];//标记每个结点,用0或者1来标记
initialize(s);
while(root1||!IsEmpty(s))
{
//压栈直到左子树为空
while(root1)
{
push(s,root1);
tag[s->top]=0;//将每个入栈的值都设置为0
root1=root1->lchild;
}
while(!IsEmpty(s)&&tag[s->top]==1)
{
temp=pop(s);
printf("%c->",temp->data);
}
if(!IsEmpty(s))
{
tag[s->top]=1;//将栈顶元素设置为1
root1=s->key[s->top]->rchild;//指向栈顶的右孩子。
}
}
}
建立二叉树
BitTree Create_tree()
{
BitTree T;
char ch;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else
{
T=(BitTree)malloc(sizeof(Node));
T->data=ch;
T->lchild=Create_tree();
T->rchild=Create_tree();
}
return T;
}
递归先序
void PreorderTraverse(BitTree root)
{
if(root)
{
printf("%c->",root->data);
PreorderTraverse(root->lchild);
PreorderTraverse(root->rchild);
}
}
递归中序
void InorderTraverse(BitTree root)
{
if(root)
{
PreorderTraverse(root->lchild);
printf("%c->", root->data);
PreorderTraverse(root->rchild);
}
}
递归后序
void PostorderTraverse(BitTree root)
{
if(root)
{
PreorderTraverse(root->lchild);
PreorderTraverse(root->rchild);
printf("%c->", root->data);
}
}
int main(void)
{
char ch;
printf("请输入您要输入的结点内容\n" );
BitTree bittree;
bittree=Create_tree();
printf("非递归前序序列:");
PreorderTraverse1(bittree);
printf("中序序列:");
InorderTraverse(bittree);
printf("非递归中序序列:");
InorderTraverse1(bittree);
printf("后序序列:");
PostorderTraverse(bittree);
printf("非递归后序序列:");
PostorderTraverse1(bittree);
return 0;
}
结果展示