c语言 怎样把二叉树用广义表示法打印出来
如题:创建二叉树后 用广义表示法打印例打印结果:5(4(3,54(,8)),3(53,4(3,4)))
答案:先递归建立二叉树,再递归打印:
#include"stdio.h"
#include"stdlib.h"
#include"conio.h"
typedef struct binode
{ char ch;
struct binode *left,*right;
}BT;
int create(BT **);
void preorder(BT *);
void output(BT *);
main()
{ int i,j;
BT *b=NULL;
printf("input the char:");
create(&b);
printf("the preorder is:");
preorder(b);
printf("\nthe kuo hao biao shi is:");
output(b);
getch();
}
int create(BT **b)
{
char ch;
ch=getchar();
if(ch=='#')
{ *b=NULL;
}
else
{ *b=(BT *)malloc(sizeof(BT));
(*b)->ch=ch;
create(&((*b)->left));
create(&((*b)->right));
}
return 1;
}
void preorder(BT *r)
{ if(r!=NULL)
{
printf("%c",r->ch);
preorder(r->left);
preorder(r->right);
}
}
void output(BT *r)
{
if(r!=NULL)
{ printf("%c",r->ch);
if(r->left!=NULL||r->right!=NULL)
{ printf("(");
output(r->left);
if(r->right!=NULL)
printf(",");
output(r->right);
printf(")");
}
}
}