//二叉数组的创建
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct node
{
char data;
struct node *lchild,*rchild;
}BTNode; //二叉数组的基本结点
//创建二叉数组传入一个头结点传入一个字符数组
void CreateBTree(BTNode* &bt,char *str)
{
BTNode *st[MaxSize],*p=NULL;
int top = -1,k,j=0;
char ch;
bt = NULL; //赋值为空
ch = str[j];
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(bt == NULL)
bt = p; //对二叉数组的头结点进行赋值
else
{
switch(k)
{
case 1:
st[top]->lchild = p;
break;
case 2:
st[top]->rchild = p;
break;
}
}
} //end of switch
j++;
ch = str[j];
} //end of while
}
//二叉数组的输出
void DisBTree(BTNode *bt)
{
BTNode *p = new BTNode;
p = bt;
if(p)
{
DisBTree(bt->lchild);
DisBTree(bt->rchild);
printf("%c ""\n",bt->data);
}
}
//二叉数组的测试以及后遍历
int main()
{
BTNode *a;
char b[] = "a(b(c,d),e(f,g))";
a = NULL;
CreateBTree(a,b);
DisBTree(a);
system("pause");
}
版权声明:本文为博主原创文章,未经博主允许不得转载。