#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Node{ // 之定义二叉树的节点
char data;
struct Node *lchild ,*rchild;//node 结点 struct 定义一个node数据类型
}BinTNode;//*BinTree; //struct前加typedef则BinTNode等同于int float的地位
typedef BinTNode *BinTree; // BinTree为定义的数据类型
int NodeNum,leaf; // NodeNum为节点数,leaf为叶子数
//要求输入先序序列,其中加入虚结点#为空指针
BinTree CreateBinTree(void){
BinTree T; //定义一个二叉树指针T
char ch;
if((ch=getchar())=='#')
{
return (NULL);//读入#,返回空指针,意思#没用
}
else{
T=(BinTNode *)malloc(sizeof(BinTNode));//生成结点
//声明一段长度为BinTNode这种类型大小的内存,malloc分配地址
T->data=ch;
T->lchild=CreateBinTree(); //构造左子树
T->rchild=CreateBinTree(); //构造右子树
}
return (T);
}
void Xian(BinTree T)
{ if(T==NULL)
return ;
else
{
printf("%c ",T->data);
Xian(T->lchild);
Xian(T->rchild);
}
}
void Zhong(BinTree T)
{ if(T==NULL)
return ;
else
{
Zhong(T->lchild);
printf("%c ",T->data);
Zhong(T->rchild);
}
}
void Hou(BinTree T)
{ if(T==NULL)
return ;
else
{
Hou(T->lchild);
Hou(T->rchild);
printf("%c ",T->data);
}
}
int main()
{ BinTree T=CreateBinTree();
printf("递归前序遍历------");
Xian(T);
printf("\n");
printf("递归中序遍历------");
Zhong(T);
printf("\n");
printf("递归后序遍历------");
Hou(T);
printf("\n");
return 0;
}
1.代码可直接使用
2.注意输入先序序列的格式