关于二叉树的问题,请高手帮帮忙!!!

huangbo0603 huangbo0603 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
首先我建立了一个以先序遍历的方法建立了二叉树,运行在数据输入时格式总是不对,还请各位帮忙解决一下!
代码如下:
# include <stdio.h>
# include <stdlib.h>
# define TRUE 1
# define FALSE 0
#define Stack_Size 50

typedef char DataType;
typedef struct node {
DataType data;
struct node *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree *bt )//建立二叉树
{
char ch='0';
ch=getchar();


if(ch=='.')
{
*bt=NULL;
return;
}
else
{
/* if (!(*bt = (BiTNode *)malloc(sizeof(BiTNode))))
exit (OVERFLOW);*/
*bt=(BiTree)malloc(sizeof(BiTNode));
(*bt)->data=ch;
CreateBiTree(&((*bt)->lchild));
CreateBiTree(&((*bt)->rchild));

}
// printf("二叉树已建立成功!");
}
void inorder(BiTree root)//中序非递归遍历二叉树
{
BiTNode *p;
int top;
BiTree S[Stack_Size];
top=0;
p=root;
//printf("ZYZ\n");
do{
while(p!=NULL)
{
if(top>Stack_Size-1)
{
printf("栈满\n");
return;
}
else
{
top=top+1;
S[top]=p;
p=p->lchild;

}
}
if (top!=0)
{
p=S[top];
top=top-1;
printf("%c",p->data);
p=p->rchild;
}
}while(p!=NULL||top!=0);
}

void PreOrder(BiTree root)//实现中序遍历递归
//root指向二叉树根结点
{ if(root!=NULL)
{

PreOrder(root->lchild);
printf("%c",root->data);
PreOrder(root->rchild);
}
}
void PostOrder (BiTree root)
{
if(root!=NULL)
{

PostOrder(root->rchild);
PostOrder(root->lchild);
printf("%c",root->data);
}
}
void main( )
{
BiTree T=NULL;
int xz=1;
//char ch;
while(1) {
printf(" 二叉树的建立及遍历\n");
printf("==========================\n");
printf(" 1、建立二叉树存储结构 \n");
printf(" 2、二叉树的前序遍历(递归)\n");
printf(" 3、二叉树的中序遍历(非递归)\n");
printf(" 4、二叉树的后序遍历");
printf(" 0、退 出 系 统 \n");
printf("===========================\n");
printf(" 请选择:0--4 ");
scanf("%d",&xz);
switch(xz)
{ case 0:
printf("再见!\n");
return;
case 1:
//ch=getchar();
printf("\n");
printf("按扩展先序遍历序列输入二叉树各结点值:");
CreateBiTree(&T);
printf("\n二叉树的链式存储结构建立完成!\n");
printf("\n");
break;
case 2:
printf("二叉树先序遍历序列为:");
if(T) PreOrder(T);
else printf("\n空树");
printf("\n");
printf("\n");
//xz=1;
break;
case 3:
printf("二叉树中序遍历序列为:");
inorder(T);
printf("\n");
// xz=1;
break;
case 4:
printf("二叉树中序遍历序列为:");
PostOrder(T);
printf("\n");
//xz=1;
break;
default:
printf("你输入有误请从新输入!");
break;
}
}

}//main
...全文

相关推荐

评论 10
收藏 已收藏
分享
返回顶部
huangbo0603
C语言 70,039 成员 243,237 内容