广义表输出二叉树
广义表输出二叉树用到的主要是递归,递归的整个过程类似于栈,一层一层进去,最终会一层一层退出来,进去和退出的顺序跟栈的性质一致。
#include<stdio.h>
#include<stdlib.h>
typedef struct tnode{
char data; //二叉树结点值
struct tnode *lchild,*rchild;
}BT;
/*以先序序列输入结点的值*/
BT *CreateBTree(){
BT *t;
char ch;
scanf("%c",&ch);
getchar();
if(ch == '0') //读入'0'时,将相应结点置空
t = NULL;
else{
t = (BT *)malloc(sizeof(BT)); //新建结点
//【结构体指针类型名 = (结构体类型名*) malloc (sizeof(结构体类型名))】
t->data = ch;
printf("请输入%c结点的左孩子的结点:",t->data);
t->lchild = CreateBTree();
printf("请输入%c结点的右孩子的结点:",t->data);
t->rchild = CreateBTree();
}
return t;
}
void ShowBTree(BT *T){
if(T != NULL){
printf("%c",T->data); //输入该结点数据域
if(T->lchild != NULL){
printf("(");
ShowBTree(T->lchild);
if(T->rchild != NULL){
printf(",");
ShowBTree(T->rchild);
}
printf(")");
}
else if(T->rchild != NULL ){ //若左子树为空,右子树不为空
printf("(");
ShowBTree(T->lchild);
if(T->rchild != NULL){
printf(",");
ShowBTree(T->rchild);
}
printf(")");
}
}
}
main(){
BT *T = NULL;
char flag;
printf("请按先序序列输入二叉树的结点:\n");\
printf("说明:输入结点后按回车('0'表示后继结点为空)\n");
printf("请输入根结点:");
T = CreateBTree();
printf("二叉树建立成功!\n");
printf("\n按广义表输出的二叉树为:");
ShowBTree(T);
}


