怎么用c语言实现二叉树的遍历

2024-12-03 10:38:24
推荐回答(1个)
回答1:

这是用广义表建立二叉树并先序和中序遍历二叉树
#include
#include

#define MaxSize 100

typedef struct node
{
char data;
struct node *lchild;
struct node *rchild;
}BTNode,*BiTree;

void creategeneralizelist(BiTree *b,char *str)
{
BTNode *St[MaxSize],*p=NULL;
int top=-1,flag,j;
char ch;
for(j=0;(ch=str[j])!='#';j++)
{
switch(ch)
{
case '(':
top++;
St[top]=p;
flag=1;
break;

case ')':
top--;
break;

case ',':
flag=2;
break;

default:
p=(BiTree)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=NULL;
p->rchild=NULL;
if(*b==NULL)
*b=p;
else
{
switch(flag)
{
case 1:
St[top]->lchild=p;
break;

case 2:
St[top]->rchild=p;
break;
}
}
}
}
}

void PreOrder(BiTree T)
{
if(T)
{
printf("%2c",T->data);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}

void InOrder(BiTree T)
{
if(T)
{
InOrder(T->lchild);
printf("%2c",T->data);
InOrder(T->rchild);
}
}

int main(void)
{
BiTree T=NULL;
char str[MaxSize];/*用于保存用户输入的字符*/
printf("please input a string end with #:\n");
scanf("%s",str);
creategeneralize_list(&T,str);
printf("the result ofInOrder BiTree is:\n");
/* PreOrder(T);*/
InOrder(T);
getch();
return 1;

}