Description:如果用大写字母标识二叉树结点,则一棵二叉树可以用符合下面语法图的字符序列表示。是编写递归程序,由这种形式的字符序列,建立相应的二叉树链表存储结构;
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
typedef struct node{
char info;
node* lchild;
node* rchild;
}node, *Pnode;//树的结构体
Pnode creat(){//创建树,另一种我也不知道为啥AC不了
Pnode T=(Pnode)malloc(sizeof(node));
T->rchild=NULL;
T->lchild=NULL; //此处必须要初始化T的左右孩子
char s1=getchar();
char s2=getchar();
if(s1==',') {
T->info=s2;
s1=getchar();
if(s1=='('){
T->lchild=creat();
T->rchild=creat();
}}//case 1:此时节点的info为s2,则会在输入一个‘(’,递归创建树
else{
T->info=s1;
if(s2=='('){
T->lchild=creat();
T->rchild=creat();
}
}//case 2:这种情况下结点的值为s1,则s2为‘(’, 递归创建树
return T;
}
void output(Pnode T){//先序输出树
if(T==NULL) return;//递归结束条件
else{
cout<<T->info;
output(T->lchild);
output(T->rchild);
}
}
int main(){
Pnode T;
T=creat();//树的创建是本题的关键
output (T);
}