c语言二叉树的创建及中序遍历的递归与非递归算法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include "stdio.h"
#include "stdlib.h"
typedef struct bnode{
char data;
struct bnode*lchild,*rchild;
}Bnode,*BTree;//创建结点
BTree CreatBtree();
void InOrder(BTree t);
void PostOrder(BTree t);//函数声明

void main()
{int x;
BTree s;
s=(Bnode*)malloc(sizeof(Bnode));
printf("请按先序遍历输入,其中#表示空结点\n例如:AB#D##CE##F##\n");
s=CreatBtree();
printf("请输入实现方式\n1:非递归方式,2:递归方式\n");
scanf("%d",&x);
if(x==1)InOrder(s);
else if(x==2)PostOrder(s);
else printf("输入错误\n");
printf("\n");
}

BTree CreatBtree()
{BTree t;
char ch;
ch=getchar();
if(ch=='#')t=NULL;
else{t=(Bnode*)malloc(sizeof(Bnode));
t->data=ch;
t->lchild=CreatBtree();
t->rchild=CreatBtree();}
return t;}//创建二叉树

void InOrder(BTree t)
{BTree p=t;
BTree stack[100];//创建栈
int top=-1;
while(p||top!=-1)
if(p)
{stack[++top]=p;
p=p->lchild;}
else{p=stack[top--];
printf("%c ",p->data);
p=p->rchild;}
}//非递归中序遍历

void PostOrder(BTree t)
{if(t)
{PostOrder(t->lchild);
printf("%c ",t->data);
PostOrder(t->rchild);}
}//递归中序遍历

相关文档
最新文档