btree.h
#ifndef BTREE_H_INCLUDED
#define BTREE_H_INCLUDED
typedef char ElemType;
#define MaxSize 101
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
void CreateBTNode(BTNode *&b,char *str);
void DispBTNode(BTNode *b);
void DestroyBTNode(BTNode *&b);
void PreOrder(BTNode *b);
void InOrder(BTNode *b);
void PostOrder(BTNode *b);
#endif // BTREE_H_INCLUDED
main.cpp
#ifndef BTREE_H_INCLUDED
#define BTREE_H_INCLUDED
typedef char ElemType;
#define MaxSize 101
typedef struct node
{
ElemType data;
struct node *lchild;
struct node *rchild;
}BTNode;
void CreateBTNode(BTNode *&b,char *str);
void DispBTNode(BTNode *b);
void DestroyBTNode(BTNode *&b);
void PreOrder(BTNode *b);
void InOrder(BTNode *b);
void PostOrder(BTNode *b);
#endif // BTREE_H_INCLUDED
btree.cpp
#include "btree.h"
#include <iostream>
#include<malloc.h>
#include<cstdio>
void CreateBTNode(BTNode *&b,char *str)
{
BTNode *St[MaxSize],*p;
int top=-1,k,j=0;
char ch;
ch=str[j];
b=NULL;
while(ch!='\0')
{
switch(ch)
{
case '(':
top++;
St[top]=p;
k=1;
break;
case ')':
top--;
break;
case ',':
k=2;
break;
default:
p=(BTNode *)malloc(sizeof(BTNode));
p->data=ch;
p->lchild=p->rchild=NULL;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1:
St[top]->lchild=p;
break;
case 2:
St[top]->rchild=p;
break;
}
}
}
j++;
ch=str[j];
}
}
void DispBTNode(BTNode *b)
{
if(b!=NULL)
{
printf("%c",b->data);
if(b->lchild!=NULL||b->rchild!=NULL)
{
printf("(");
DispBTNode(b->lchild);
if(b->rchild!=NULL)
printf(",");
DispBTNode(b->rchild);
printf(")");
}
}
}
void DestroyBTNode(BTNode *&b)
{
if(b==NULL)
{
DestroyBTNode(b->lchild);
DestroyBTNode(b->rchild);
free(b);
}
}
void PreOrder(BTNode *b)
{
if(b!=NULL)
{
printf("%c ",b->data);
PreOrder(b->lchild);
PreOrder(b->rchild);
}
}
void InOrder(BTNode *b)
{
if(b!=NULL)
{
InOrder(b->lchild);
printf("%c ",b->data);
InOrder(b->rchild);
}
}
void PostOrder(BTNode *b)
{
if(b!=NULL)
{
PostOrder(b->lchild);
PostOrder(b->rchild);
printf("%c ",b->data);
}
}