69,374
社区成员
发帖
与我相关
我的任务
分享
#include <malloc.h>
#include <iostream>
#define maxsize 20
typedef struct node//定义二叉树的类型
{
char data;
struct node *lchild,*rchild;
int degree;//改结点的度
}Bitree;
Bitree *Q[maxsize];//队列Q为指针类型
Bitree *Creatree()//建立二叉树,返回根子针
{
char ch;
int front,rear;
Bitree *T,*S;
T=NULL;//置空队列-----------
front=1;rear=0;
printf("创建一棵二叉树(@ 虚结点标志,+结束标志):\n");
printf("请输入结点信息:\n");
ch=getchar();//输入第一个结点信息
while(ch!='+')
{
S=NULL;//如果输入的是虚结点就不需要申请空间
if(ch!='@')
{
S=(Bitree*)malloc(sizeof(Bitree));
S->data=ch;
S->lchild=S->rchild=NULL;//左右子树置空
S->degree=0;//根结点置
}
rear++;Q[rear]=S;//将虚结点指针NULL或者新结点地址入队
if(rear==1)
T=S;//输入的第一个结点为根结点
else
{
if(S!=NULL&&Q[front]!=NULL)//孩子和双亲都不是虚结点
{
if(rear%2==0)
Q[front]->lchild=S;
else
Q[front]->rchild=S;
S->degree=Q[front]->degree+1;//存储个结点度,记录各结点的深度
}
if(rear%2==1)
front++;//结点*Q[front]的两个孩子已处理完毕front+1
}
ch=getchar();
}
return T;
}
void Inorder(Bitree*T)
{
int i;
if(T)
{
Inorder(T->rchild);
for(i=0;i<T->degree;i++)
{
printf("\t");
}
printf("%4c\n",T->data);
Inorder(T->lchild);
}
}
void introduce()
{
printf("***********欢迎使用打印二叉树************\n");
}
void main()
{
Bitree *TR;
introduce();
TR=Creatree();
printf("打印二叉树的结果:\n");
Inorder(TR);
}