①建立二叉树,采用二叉链表结构
②先序、中序、后续遍历二叉树
③销毁二叉树
#include<stdio.h>
#include<malloc.h>
#include <stdlib.h>
#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int Boolean;
typedef char TElemType;
typedef struct BiTNode{
TElemType data;//数据
struct BiTNode *lchild,*rchild;//左右孩子指针
}BiTNode,*BiTree;
BiTree CreateBiTree(BiTree T){
char ch;
ch=getchar();
if(ch==' ') T=NULL;
else{
T=(BiTNode *)malloc(sizeof(BiTNode));
T->data =ch;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
return T;
}
void preorder(BiTree T){//先序
if(T){
printf("%c\t",T->data );
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(BiTree T){//中序
if(T){
preorder(T->lchild);
printf("%c\t",T->data );
preorder(T->rchild);
}
}
void postorder(BiTree T){//后序
if(T){
preorder(T->lchild);
preorder(T->rchild);
printf("%c\t",T->data );
}
}
void DestroyBiTree(BiTree T)
{
if(T)
{
DestroyBiTree(T->lchild);
DestroyBiTree(T->rchild);
free(T);
}
}
int main()
{
BiTree T;
printf("输入二叉树数据,以“ ”空格为节点:");
T=CreateBiTree(T);
printf("先序排序:");
preorder(T);
printf("\n");
printf("中序排序:");
inorder(T);
printf("\n");
printf("后序排序:");
postorder(T);
printf("\n");
DestroyBiTree(T);
return 0;
}