写一非递归算法,将数组转化为二叉链表表示的二叉树
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef int Status;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct
{
int pos;
BiTree t;
}Stack;
void CreateList(char *w,int n);
void CreateBiTree(BiTree *T,char *w,int n);
Status PreOrderTraverse(BiTree T);
Status Visit(char e);
int sum=0;
int main()
{
int n;
char *w;
printf("有多少项:");
scanf("%d",&n);
w=(char *)malloc(sizeof(char)*(n+1));
CreateList(w,n);
BiTree *T;
T=(BiTree*)malloc(sizeof(BiTree));
CreateBiTree(T,w,n);
printf("\n前序遍历结果:");
PreOrderTraverse(*T);
return 0;
}
//---创建线性表---//
void CreateList(char *w,int n)
{
int i;
for(i=1;i<=n;i++)
{
fflush(stdin);
printf("请输入第%d项:",i);
scanf("%c",&w[i]);
}
}
//---按从上往下层创建二叉树---//
void CreateBiTree(BiTree *T,char *w,int n)
{
Stack S[MAXSIZE+1];
int top=0;
*T=(BiTree)malloc(sizeof(BiTNode));
(*T)->data=w[1];
top++;
S[top].t=*T;
S[top].pos=1;
while(top)
{
S[0]=S[top--];
int pos;
pos=S[0].pos;
if(2*pos<=n && w[2*pos]!='#')
{
BiTree p;
p=(BiTree)malloc(sizeof(BiTNode));
p->data=w[2*pos];
S[0].t->lchild=p;
top++;
S[top].t=p;
S[top].pos=2*pos;
}
else
S[0].t->lchild=NULL;
if(2*pos+1<=n && w[2*pos+1]!='#')
{
BiTree p;
p=(BiTree)malloc(sizeof(BiTNode));
p->data=w[2*pos+1];
S[0].t->rchild=p;
top++;
S[top].t=p;
S[top].pos=2*pos+1;
}
else
S[0].t->rchild=NULL;
}
}
Status Visit(char e)
{
printf("%c ",e);
return OK;
}
//---前序遍历二叉树---//
Status PreOrderTraverse(BiTree T)
{
if(T)
{
if(Visit(T->data))
if(PreOrderTraverse(T->lchild))
if(PreOrderTraverse(T->rchild))
return OK;
return ERROR;
}
else
return OK;
}