二叉树的建立与遍历(C++)

2025-01-31 21:55:57
推荐回答(1个)
回答1:

#include "stdlib.h"
#include "stdio.h"

typedef struct node
{
int ltag,rtag;
char data;
struct node *lchild,*rchild;
}bithptr;

bithptr *Creat()
{
char ch; ///建立儿叉数
int front,rear;
bithptr *Q[50];
bithptr *root,*s;
root=NULL;
front=1;
rear=0;
cin>>ch;
while(ch!='#')
{
s=NULL;
if(ch!='@') ///'@'表示虚结点
{
s=new bithptr;
s->data=ch;
s->ltag=0;
s->rtag=0;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)
root=s;
else
{
if(s && Q[front])
{
if(rear%2==0)
Q[front]->lchild=s;
else
Q[front]->rchild=s;
}
if(rear%2==1)
front++;
}
cin>>ch;
}
return root;
}
INORDER(bithptr *t)//中序
{
if(t)
{
INORDER(t->lchild);
printf("\t%c\n",t->data);
INORDER(t->rchild);
}
}
PREORDER(bithptr *t)//前序
{
if(t)
{
printf("\t%c\n",t->data);
PREORDER(t->lchild);
PREORDER(t->rchild);
}
}
POSTORDER(bithptr *t)//后序
{
if(t)
{
POSTORDER(t->lchild);
POSTORDER(t->rchild);
printf("\t%c\n",t->data);
}
}

void main()
{
bithptr *t;
printf("请输入结点:");
t=Creat();
printf("\n")
printf("前序:")
PREORDER(t);
printf("中序:")
INORDER(t);
printf("后续:")
POSTORDER(t);
}